Completed
Push — master ( 087bb5...e5b20b )
by
unknown
143:24 queued 132:38
created

Jetpack_Gutenberg::load_scripts_as_required()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 36

Duplication

Lines 5
Ratio 13.89 %

Importance

Changes 0
Metric Value
cc 7
nc 7
nop 2
dl 5
loc 36
rs 8.4106
c 0
b 0
f 0
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\Blocks;
10
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
11
use Automattic\Jetpack\Constants;
12
use Automattic\Jetpack\Status;
13
14
/**
15
 * Wrapper function to safely register a gutenberg block type
16
 *
17
 * @deprecated 9.1.0 Use Automattic\\Jetpack\\Blocks::jetpack_register_block instead
18
 *
19
 * @see register_block_type
20
 *
21
 * @since 6.7.0
22
 *
23
 * @param string $slug Slug of the block.
24
 * @param array  $args Arguments that are passed into register_block_type.
25
 *
26
 * @return WP_Block_Type|false The registered block type on success, or false on failure.
27
 */
28
function jetpack_register_block( $slug, $args = array() ) {
29
	_deprecated_function( __METHOD__, '9.1.0', 'Automattic\\Jetpack\\Blocks::jetpack_register_block' );
30
	return Blocks::jetpack_register_block( $slug, $args );
31
}
32
33
/**
34
 * Helper function to register a Jetpack Gutenberg plugin
35
 *
36
 * @deprecated 7.1.0 Use Jetpack_Gutenberg::set_extension_available() instead
37
 *
38
 * @param string $slug Slug of the plugin.
39
 *
40
 * @since 6.9.0
41
 *
42
 * @return void
43
 */
44
function jetpack_register_plugin( $slug ) {
45
	_deprecated_function( __FUNCTION__, '7.1', 'Jetpack_Gutenberg::set_extension_available' );
46
47
	Jetpack_Gutenberg::register_plugin( $slug );
0 ignored issues
show
Deprecated Code introduced by
The method Jetpack_Gutenberg::register_plugin() has been deprecated with message: 7.1.0 Use Jetpack_Gutenberg::set_extension_available() 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...
48
}
49
50
/**
51
 * Set the reason why an extension (block or plugin) is unavailable
52
 *
53
 * @deprecated 7.1.0 Use Jetpack_Gutenberg::set_extension_unavailable() instead
54
 *
55
 * @param string $slug Slug of the block.
56
 * @param string $reason A string representation of why the extension is unavailable.
57
 *
58
 * @since 7.0.0
59
 *
60
 * @return void
61
 */
62
function jetpack_set_extension_unavailability_reason( $slug, $reason ) {
63
	_deprecated_function( __FUNCTION__, '7.1', 'Jetpack_Gutenberg::set_extension_unavailable' );
64
65
	Jetpack_Gutenberg::set_extension_unavailability_reason( $slug, $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...
66
}
67
68
/**
69
 * General Gutenberg editor specific functionality
70
 */
71
class Jetpack_Gutenberg {
72
73
	/**
74
	 * Only these extensions can be registered. Used to control availability of beta blocks.
75
	 *
76
	 * @var array Extensions allowed list.
77
	 */
78
	private static $extensions = array();
79
80
	/**
81
	 * Keeps track of the reasons why a given extension is unavailable.
82
	 *
83
	 * @var array Extensions availability information
84
	 */
85
	private static $availability = array();
86
87
	/**
88
	 * A cached array of the fully processed availability data. Keeps track of
89
	 * reasons why an extension is unavailable or missing.
90
	 *
91
	 * @var array Extensions availability information.
92
	 */
93
	private static $cached_availability = null;
94
95
	/**
96
	 * Check to see if a minimum version of Gutenberg is available. Because a Gutenberg version is not available in
97
	 * php if the Gutenberg plugin is not installed, if we know which minimum WP release has the required version we can
98
	 * optionally fall back to that.
99
	 *
100
	 * @param array  $version_requirements An array containing the required Gutenberg version and, if known, the WordPress version that was released with this minimum version.
101
	 * @param string $slug The slug of the block or plugin that has the gutenberg version requirement.
102
	 *
103
	 * @since 8.3.0
104
	 *
105
	 * @return boolean True if the version of gutenberg required by the block or plugin is available.
106
	 */
107 View Code Duplication
	public static function is_gutenberg_version_available( $version_requirements, $slug ) {
108
		global $wp_version;
109
110
		// Bail if we don't at least have the gutenberg version requirement, the WP version is optional.
111
		if ( empty( $version_requirements['gutenberg'] ) ) {
112
			return false;
113
		}
114
115
		// If running a local dev build of gutenberg plugin GUTENBERG_DEVELOPMENT_MODE is set so assume correct version.
116
		if ( defined( 'GUTENBERG_DEVELOPMENT_MODE' ) && GUTENBERG_DEVELOPMENT_MODE ) {
117
			return true;
118
		}
119
120
		$version_available = false;
121
122
		// If running a production build of the gutenberg plugin then GUTENBERG_VERSION is set, otherwise if WP version
123
		// with required version of Gutenberg is known check that.
124
		if ( defined( 'GUTENBERG_VERSION' ) ) {
125
			$version_available = version_compare( GUTENBERG_VERSION, $version_requirements['gutenberg'], '>=' );
126
		} elseif ( ! empty( $version_requirements['wp'] ) ) {
127
			$version_available = version_compare( $wp_version, $version_requirements['wp'], '>=' );
128
		}
129
130
		if ( ! $version_available ) {
131
			self::set_extension_unavailable(
132
				$slug,
133
				'incorrect_gutenberg_version',
134
				array(
135
					'required_feature' => $slug,
136
					'required_version' => $version_requirements,
137
					'current_version'  => array(
138
						'wp'        => $wp_version,
139
						'gutenberg' => defined( 'GUTENBERG_VERSION' ) ? GUTENBERG_VERSION : null,
140
					),
141
				)
142
			);
143
		}
144
145
		return $version_available;
146
	}
147
148
	/**
149
	 * Prepend the 'jetpack/' prefix to a block name
150
	 *
151
	 * @param string $block_name The block name.
152
	 *
153
	 * @return string The prefixed block name.
154
	 */
155
	private static function prepend_block_prefix( $block_name ) {
156
		return 'jetpack/' . $block_name;
157
	}
158
159
	/**
160
	 * Remove the 'jetpack/' or jetpack-' prefix from an extension name
161
	 *
162
	 * @param string $extension_name The extension name.
163
	 *
164
	 * @return string The unprefixed extension name.
165
	 */
166
	public static function remove_extension_prefix( $extension_name ) {
167 View Code Duplication
		if ( 0 === strpos( $extension_name, 'jetpack/' ) || 0 === strpos( $extension_name, 'jetpack-' ) ) {
168
			return substr( $extension_name, strlen( 'jetpack/' ) );
169
		}
170
		return $extension_name;
171
	}
172
173
	/**
174
	 * Whether two arrays share at least one item
175
	 *
176
	 * @param array $a An array.
177
	 * @param array $b Another array.
178
	 *
179
	 * @return boolean True if $a and $b share at least one item
180
	 */
181
	protected static function share_items( $a, $b ) {
182
		return count( array_intersect( $a, $b ) ) > 0;
183
	}
184
185
	/**
186
	 * Register a plugin
187
	 *
188
	 * @deprecated 7.1.0 Use Jetpack_Gutenberg::set_extension_available() instead
189
	 *
190
	 * @param string $slug Slug of the plugin.
191
	 */
192
	public static function register_plugin( $slug ) {
193
		_deprecated_function( __METHOD__, '7.1', 'Jetpack_Gutenberg::set_extension_available' );
194
195
		self::set_extension_available( $slug );
196
	}
197
198
	/**
199
	 * Set a (non-block) extension as available
200
	 *
201
	 * @param string $slug Slug of the extension.
202
	 */
203
	public static function set_extension_available( $slug ) {
204
		self::$availability[ self::remove_extension_prefix( $slug ) ] = true;
205
	}
206
207
	/**
208
	 * Set the reason why an extension (block or plugin) is unavailable
209
	 *
210
	 * @param string $slug Slug of the extension.
211
	 * @param string $reason A string representation of why the extension is unavailable.
212
	 * @param array  $details A free-form array containing more information on why the extension is unavailable.
213
	 */
214
	public static function set_extension_unavailable( $slug, $reason, $details = array() ) {
215
		if (
216
			// Extensions that require a plan may be eligible for upgrades.
217
			'missing_plan' === $reason
218
			&& (
219
				/**
220
				 * Filter 'jetpack_block_editor_enable_upgrade_nudge' with `true` to enable or `false`
221
				 * to disable paid feature upgrade nudges in the block editor.
222
				 *
223
				 * When this is changed to default to `true`, you should also update `modules/memberships/class-jetpack-memberships.php`
224
				 * See https://github.com/Automattic/jetpack/pull/13394#pullrequestreview-293063378
225
				 *
226
				 * @since 7.7.0
227
				 *
228
				 * @param boolean
229
				 */
230
				! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false )
231
				/** This filter is documented in _inc/lib/admin-pages/class.jetpack-react-page.php */
232
				|| ! apply_filters( 'jetpack_show_promotions', true )
233
			)
234
		) {
235
			// The block editor may apply an upgrade nudge if `missing_plan` is the reason.
236
			// Add a descriptive suffix to disable behavior but provide informative reason.
237
			$reason .= '__nudge_disabled';
238
		}
239
240
		self::$availability[ self::remove_extension_prefix( $slug ) ] = array(
241
			'reason'  => $reason,
242
			'details' => $details,
243
		);
244
	}
245
246
	/**
247
	 * Set the reason why an extension (block or plugin) is unavailable
248
	 *
249
	 * @deprecated 7.1.0 Use set_extension_unavailable() instead
250
	 *
251
	 * @param string $slug Slug of the extension.
252
	 * @param string $reason A string representation of why the extension is unavailable.
253
	 */
254
	public static function set_extension_unavailability_reason( $slug, $reason ) {
255
		_deprecated_function( __METHOD__, '7.1', 'Jetpack_Gutenberg::set_extension_unavailable' );
256
257
		self::set_extension_unavailable( $slug, $reason );
258
	}
259
260
	/**
261
	 * Set up a list of allowed block editor extensions
262
	 *
263
	 * @return void
264
	 */
265
	public static function init() {
266
		if ( ! self::should_load() ) {
267
			return;
268
		}
269
270
		/**
271
		 * Alternative to `JETPACK_BETA_BLOCKS`, set to `true` to load Beta Blocks.
272
		 *
273
		 * @since 6.9.0
274
		 *
275
		 * @param boolean
276
		 */
277
		if ( apply_filters( 'jetpack_load_beta_blocks', false ) ) {
278
			Constants::set_constant( 'JETPACK_BETA_BLOCKS', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
279
		}
280
281
		/**
282
		 * Alternative to `JETPACK_EXPERIMENTAL_BLOCKS`, set to `true` to load Experimental Blocks.
283
		 *
284
		 * @since 8.4.0
285
		 *
286
		 * @param boolean
287
		 */
288
		if ( apply_filters( 'jetpack_load_experimental_blocks', false ) ) {
289
			Constants::set_constant( 'JETPACK_EXPERIMENTAL_BLOCKS', true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
290
		}
291
292
		/**
293
		 * Filter the list of block editor extensions that are available through Jetpack.
294
		 *
295
		 * @since 7.0.0
296
		 *
297
		 * @param array
298
		 */
299
		self::$extensions = apply_filters( 'jetpack_set_available_extensions', self::get_available_extensions() );
300
301
		/**
302
		 * Filter the list of block editor plugins that are available through Jetpack.
303
		 *
304
		 * @deprecated 7.0.0 Use jetpack_set_available_extensions instead
305
		 *
306
		 * @since 6.8.0
307
		 *
308
		 * @param array
309
		 */
310
		self::$extensions = apply_filters( 'jetpack_set_available_blocks', self::$extensions );
311
312
		/**
313
		 * Filter the list of block editor plugins that are available through Jetpack.
314
		 *
315
		 * @deprecated 7.0.0 Use jetpack_set_available_extensions instead
316
		 *
317
		 * @since 6.9.0
318
		 *
319
		 * @param array
320
		 */
321
		self::$extensions = apply_filters( 'jetpack_set_available_plugins', self::$extensions );
322
	}
323
324
	/**
325
	 * Resets the class to its original state
326
	 *
327
	 * Used in unit tests
328
	 *
329
	 * @return void
330
	 */
331
	public static function reset() {
332
		self::$extensions          = array();
333
		self::$availability        = array();
334
		self::$cached_availability = null;
0 ignored issues
show
Documentation Bug introduced by
It seems like null of type null is incompatible with the declared type array of property $cached_availability.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
335
	}
336
337
	/**
338
	 * Return the Gutenberg extensions (blocks and plugins) directory
339
	 *
340
	 * @return string The Gutenberg extensions directory
341
	 */
342
	public static function get_blocks_directory() {
343
		/**
344
		 * Filter to select Gutenberg blocks directory
345
		 *
346
		 * @since 6.9.0
347
		 *
348
		 * @param string default: '_inc/blocks/'
349
		 */
350
		return apply_filters( 'jetpack_blocks_directory', '_inc/blocks/' );
351
	}
352
353
	/**
354
	 * Checks for a given .json file in the blocks folder.
355
	 *
356
	 * @param string $preset The name of the .json file to look for.
357
	 *
358
	 * @return bool True if the file is found.
359
	 */
360
	public static function preset_exists( $preset ) {
361
		return file_exists( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' );
362
	}
363
364
	/**
365
	 * Decodes JSON loaded from a preset file in the blocks folder
366
	 *
367
	 * @param string $preset The name of the .json file to load.
368
	 *
369
	 * @return mixed Returns an object if the file is present, or false if a valid .json file is not present.
370
	 */
371
	public static function get_preset( $preset ) {
372
		return json_decode(
373
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
374
			file_get_contents( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' )
375
		);
376
	}
377
378
	/**
379
	 * Returns a list of Jetpack Gutenberg extensions (blocks and plugins), based on index.json
380
	 *
381
	 * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
382
	 */
383
	public static function get_jetpack_gutenberg_extensions_allowed_list() {
384
		$preset_extensions_manifest = self::preset_exists( 'index' )
385
			? self::get_preset( 'index' )
386
			: (object) array();
387
		$blocks_variation           = self::blocks_variation();
388
389
		return self::get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation );
390
	}
391
392
	/**
393
	 * Returns a list of Jetpack Gutenberg extensions (blocks and plugins), based on index.json
394
	 *
395
	 * @deprecated 8.7.0 Use get_jetpack_gutenberg_extensions_allowed_list()
396
	 *
397
	 * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
398
	 */
399
	public static function get_jetpack_gutenberg_extensions_whitelist() {
400
		_deprecated_function( __FUNCTION__, 'jetpack-8.7.0', 'Jetpack_Gutenberg::get_jetpack_gutenberg_extensions_allowed_list' );
401
		return self::get_jetpack_gutenberg_extensions_allowed_list();
402
	}
403
404
	/**
405
	 * Returns a diff from a combined list of allowed extensions and extensions determined to be excluded
406
	 *
407
	 * @param  array $allowed_extensions An array of allowed extensions.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $allowed_extensions not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
408
	 *
409
	 * @return array A list of blocks: eg array( 'publicize', 'markdown' )
410
	 */
411
	public static function get_available_extensions( $allowed_extensions = null ) {
412
		$exclusions         = get_option( 'jetpack_excluded_extensions', array() );
413
		$allowed_extensions = is_null( $allowed_extensions ) ? self::get_jetpack_gutenberg_extensions_allowed_list() : $allowed_extensions;
414
415
		return array_diff( $allowed_extensions, $exclusions );
416
	}
417
418
	/**
419
	 * Return true if the extension has been registered and there's nothing in the availablilty array.
420
	 *
421
	 * @param string $extension The name of the extension.
422
	 *
423
	 * @return bool whether the extension has been registered and there's nothing in the availablilty array.
424
	 */
425
	public static function is_registered_and_no_entry_in_availability( $extension ) {
426
		return self::is_registered( 'jetpack/' . $extension ) && ! isset( self::$availability[ $extension ] );
427
	}
428
429
	/**
430
	 * Return true if the extension has a true entry in the availablilty array.
431
	 *
432
	 * @param string $extension The name of the extension.
433
	 *
434
	 * @return bool whether the extension has a true entry in the availablilty array.
435
	 */
436
	public static function is_available( $extension ) {
437
		return isset( self::$availability[ $extension ] ) && true === self::$availability[ $extension ];
438
	}
439
440
	/**
441
	 * Get the availability of each block / plugin, or return the cached availability
442
	 * if it has already been calculated. Avoids re-registering extensions when not
443
	 * necessary.
444
	 *
445
	 * @return array A list of block and plugins and their availability status.
446
	 */
447
	public static function get_cached_availability() {
448
		if ( null === self::$cached_availability ) {
449
			self::$cached_availability = self::get_availability();
450
		}
451
		return self::$cached_availability;
452
	}
453
454
	/**
455
	 * Get availability of each block / plugin.
456
	 *
457
	 * @return array A list of block and plugins and their availablity status
458
	 */
459
	public static function get_availability() {
460
		/**
461
		 * Fires before Gutenberg extensions availability is computed.
462
		 *
463
		 * In the function call you supply, use `Blocks::jetpack_register_block()` to set a block as available.
464
		 * Alternatively, use `Jetpack_Gutenberg::set_extension_available()` (for a non-block plugin), and
465
		 * `Jetpack_Gutenberg::set_extension_unavailable()` (if the block or plugin should not be registered
466
		 * but marked as unavailable).
467
		 *
468
		 * @since 7.0.0
469
		 */
470
		do_action( 'jetpack_register_gutenberg_extensions' );
471
472
		$available_extensions = array();
473
474
		foreach ( self::$extensions as $extension ) {
475
			$is_available                       = self::is_registered_and_no_entry_in_availability( $extension ) || self::is_available( $extension );
476
			$available_extensions[ $extension ] = array(
477
				'available' => $is_available,
478
			);
479
480
			if ( ! $is_available ) {
481
				$reason  = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['reason'] : 'missing_module';
482
				$details = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['details'] : array();
483
				$available_extensions[ $extension ]['unavailable_reason'] = $reason;
484
				$available_extensions[ $extension ]['details']            = $details;
485
			}
486
		}
487
488
		return $available_extensions;
489
	}
490
491
	/**
492
	 * Check if an extension/block is already registered
493
	 *
494
	 * @since 7.2
495
	 *
496
	 * @param string $slug Name of extension/block to check.
497
	 *
498
	 * @return bool
499
	 */
500
	public static function is_registered( $slug ) {
501
		return WP_Block_Type_Registry::get_instance()->is_registered( $slug );
502
	}
503
504
	/**
505
	 * Check if Gutenberg editor is available
506
	 *
507
	 * @since 6.7.0
508
	 *
509
	 * @return bool
510
	 */
511
	public static function is_gutenberg_available() {
512
		return true;
513
	}
514
515
	/**
516
	 * Check whether conditions indicate Gutenberg Extensions (blocks and plugins) should be loaded
517
	 *
518
	 * Loading blocks and plugins is enabled by default and may be disabled via filter:
519
	 *   add_filter( 'jetpack_gutenberg', '__return_false' );
520
	 *
521
	 * @since 6.9.0
522
	 *
523
	 * @return bool
524
	 */
525
	public static function should_load() {
526
		if ( ! Jetpack::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
527
			return false;
528
		}
529
530
		/**
531
		 * Filter to disable Gutenberg blocks
532
		 *
533
		 * @since 6.5.0
534
		 *
535
		 * @param bool true Whether to load Gutenberg blocks
536
		 */
537
		return (bool) apply_filters( 'jetpack_gutenberg', true );
538
	}
539
540
	/**
541
	 * Only enqueue block assets when needed.
542
	 *
543
	 * @param string $type Slug of the block.
544
	 * @param array  $script_dependencies Script dependencies. Will be merged with automatically
545
	 *                                    detected script dependencies from the webpack build.
546
	 *
547
	 * @return void
548
	 */
549
	public static function load_assets_as_required( $type, $script_dependencies = array() ) {
550
		if ( is_admin() ) {
551
			// A block's view assets will not be required in wp-admin.
552
			return;
553
		}
554
555
		$type = sanitize_title_with_dashes( $type );
556
		self::load_styles_as_required( $type );
557
		self::load_scripts_as_required( $type, $script_dependencies );
558
	}
559
560
	/**
561
	 * Only enqueue block sytles when needed.
562
	 *
563
	 * @param string $type Slug of the block.
564
	 *
565
	 * @since 7.2.0
566
	 *
567
	 * @return void
568
	 */
569
	public static function load_styles_as_required( $type ) {
570
		if ( is_admin() ) {
571
			// A block's view assets will not be required in wp-admin.
572
			return;
573
		}
574
575
		// Enqueue styles.
576
		$style_relative_path = self::get_blocks_directory() . $type . '/view' . ( is_rtl() ? '.rtl' : '' ) . '.css';
577
		if ( self::block_has_asset( $style_relative_path ) ) {
578
			$style_version = self::get_asset_version( $style_relative_path );
579
			$view_style    = plugins_url( $style_relative_path, JETPACK__PLUGIN_FILE );
580
581
			// If this is a customizer preview, render the style directly to the preview after autosave.
582
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
583 View Code Duplication
			if ( is_customize_preview() && ! empty( $_GET['customize_autosaved'] ) ) {
584
				// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
585
				echo '<link rel="stylesheet" id="jetpack-block-' . esc_attr( $type ) . '" href="' . esc_attr( $view_style ) . '?ver=' . esc_attr( $style_version ) . '" media="all">';
586
			} else {
587
				wp_enqueue_style( 'jetpack-block-' . $type, $view_style, array(), $style_version );
588
			}
589
		}
590
591
	}
592
593
	/**
594
	 * Only enqueue block scripts when needed.
595
	 *
596
	 * @param string $type Slug of the block.
597
	 * @param array  $script_dependencies Script dependencies. Will be merged with automatically
598
	 *                             detected script dependencies from the webpack build.
599
	 *
600
	 * @since 7.2.0
601
	 *
602
	 * @return void
603
	 */
604
	public static function load_scripts_as_required( $type, $script_dependencies = array() ) {
605
		if ( is_admin() ) {
606
			// A block's view assets will not be required in wp-admin.
607
			return;
608
		}
609
610
		// Enqueue script.
611
		$script_relative_path  = self::get_blocks_directory() . $type . '/view.js';
612
		$script_deps_path      = JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $type . '/view.asset.php';
613
		$script_dependencies[] = 'wp-polyfill';
614
		if ( file_exists( $script_deps_path ) ) {
615
			$asset_manifest      = include $script_deps_path;
616
			$script_dependencies = array_unique( array_merge( $script_dependencies, $asset_manifest['dependencies'] ) );
617
		}
618
619
		if ( ! Blocks::is_amp_request() && self::block_has_asset( $script_relative_path ) ) {
620
			$script_version = self::get_asset_version( $script_relative_path );
621
			$view_script    = plugins_url( $script_relative_path, JETPACK__PLUGIN_FILE );
622
623
			// If this is a customizer preview, render the script directly to the preview after autosave.
624
			// phpcs:ignore WordPress.Security.NonceVerification.Recommended
625 View Code Duplication
			if ( is_customize_preview() && ! empty( $_GET['customize_autosaved'] ) ) {
626
				echo '<script id="jetpack-block-' . esc_attr( $type ) . '" src="' . esc_attr( $view_script ) . '?ver=' . esc_attr( $script_version ) . '"></script>';
627
			} else {
628
				wp_enqueue_script( 'jetpack-block-' . $type, $view_script, $script_dependencies, $script_version, false );
629
			}
630
		}
631
632
		wp_localize_script(
633
			'jetpack-block-' . $type,
634
			'Jetpack_Block_Assets_Base_Url',
635
			array(
636
				'url' => plugins_url( self::get_blocks_directory(), JETPACK__PLUGIN_FILE ),
637
			)
638
		);
639
	}
640
641
	/**
642
	 * Check if an asset exists for a block.
643
	 *
644
	 * @param string $file Path of the file we are looking for.
645
	 *
646
	 * @return bool $block_has_asset Does the file exist.
647
	 */
648
	public static function block_has_asset( $file ) {
649
		return file_exists( JETPACK__PLUGIN_DIR . $file );
650
	}
651
652
	/**
653
	 * Get the version number to use when loading the file. Allows us to bypass cache when developing.
654
	 *
655
	 * @param string $file Path of the file we are looking for.
656
	 *
657
	 * @return string $script_version Version number.
658
	 */
659
	public static function get_asset_version( $file ) {
660
		return Jetpack::is_development_version() && self::block_has_asset( $file )
661
			? filemtime( JETPACK__PLUGIN_DIR . $file )
662
			: JETPACK__VERSION;
663
	}
664
665
	/**
666
	 * Load Gutenberg editor assets
667
	 *
668
	 * @since 6.7.0
669
	 *
670
	 * @return void
671
	 */
672
	public static function enqueue_block_editor_assets() {
673
		if ( ! self::should_load() ) {
674
			return;
675
		}
676
677
		$status = new Status();
678
679
		// Required for Analytics. See _inc/lib/admin-pages/class.jetpack-admin-page.php.
680
		if ( ! $status->is_offline_mode() && Jetpack::is_connection_ready() ) {
681
			wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
682
		}
683
684
		$rtl              = is_rtl() ? '.rtl' : '';
685
		$blocks_dir       = self::get_blocks_directory();
686
		$blocks_variation = self::blocks_variation();
687
688
		if ( 'production' !== $blocks_variation ) {
689
			$blocks_env = '-' . esc_attr( $blocks_variation );
690
		} else {
691
			$blocks_env = '';
692
		}
693
694
		$editor_script = plugins_url( "{$blocks_dir}editor{$blocks_env}.js", JETPACK__PLUGIN_FILE );
695
		$editor_style  = plugins_url( "{$blocks_dir}editor{$blocks_env}{$rtl}.css", JETPACK__PLUGIN_FILE );
696
697
		$editor_deps_path = JETPACK__PLUGIN_DIR . $blocks_dir . "editor{$blocks_env}.asset.php";
698
		$editor_deps      = array( 'wp-polyfill' );
699
		if ( file_exists( $editor_deps_path ) ) {
700
			$asset_manifest = include $editor_deps_path;
701
			$editor_deps    = $asset_manifest['dependencies'];
702
		}
703
704
		$version = Jetpack::is_development_version() && file_exists( JETPACK__PLUGIN_DIR . $blocks_dir . 'editor.js' )
705
			? filemtime( JETPACK__PLUGIN_DIR . $blocks_dir . 'editor.js' )
706
			: JETPACK__VERSION;
707
708
		wp_enqueue_script(
709
			'jetpack-blocks-editor',
710
			$editor_script,
711
			$editor_deps,
712
			$version,
713
			false
714
		);
715
716
		wp_localize_script(
717
			'jetpack-blocks-editor',
718
			'Jetpack_Block_Assets_Base_Url',
719
			array(
720
				'url' => plugins_url( $blocks_dir . '/', JETPACK__PLUGIN_FILE ),
721
			)
722
		);
723
724
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
725
			$user                      = wp_get_current_user();
726
			$user_data                 = array(
727
				'userid'   => $user->ID,
728
				'username' => $user->user_login,
729
			);
730
			$blog_id                   = get_current_blog_id();
731
			$is_current_user_connected = true;
732
		} else {
733
			$user_data                 = Jetpack_Tracks_Client::get_connected_user_tracks_identity();
734
			$blog_id                   = Jetpack_Options::get_option( 'id', 0 );
735
			$is_current_user_connected = ( new Connection_Manager( 'jetpack' ) )->is_user_connected();
736
		}
737
738
		wp_localize_script(
739
			'jetpack-blocks-editor',
740
			'Jetpack_Editor_Initial_State',
741
			array(
742
				'available_blocks' => self::get_availability(),
743
				'jetpack'          => array(
744
					'is_active'                 => Jetpack::is_connection_ready(),
745
					'is_current_user_connected' => $is_current_user_connected,
746
					/** This filter is documented in class.jetpack-gutenberg.php */
747
					'enable_upgrade_nudge'      => apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false ),
748
					'is_private_site'           => '-1' === get_option( 'blog_public' ),
749
				),
750
				'siteFragment'     => $status->get_site_suffix(),
751
				'adminUrl'         => esc_url( admin_url() ),
752
				'tracksUserData'   => $user_data,
753
				'wpcomBlogId'      => $blog_id,
754
				'allowedMimeTypes' => wp_get_mime_types(),
755
			)
756
		);
757
758
		wp_set_script_translations( 'jetpack-blocks-editor', 'jetpack' );
759
760
		wp_enqueue_style( 'jetpack-blocks-editor', $editor_style, array(), $version );
761
	}
762
763
	/**
764
	 * Some blocks do not depend on a specific module,
765
	 * and can consequently be loaded outside of the usual modules.
766
	 * We will look for such modules in the extensions/ directory.
767
	 *
768
	 * @since 7.1.0
769
	 */
770
	public static function load_independent_blocks() {
771
		if ( self::should_load() ) {
772
			/**
773
			 * Look for files that match our list of available Jetpack Gutenberg extensions (blocks and plugins).
774
			 * If available, load them.
775
			 */
776
			foreach ( self::$extensions as $extension ) {
777
				$extension_file_glob = glob( JETPACK__PLUGIN_DIR . 'extensions/*/' . $extension . '/' . $extension . '.php' );
778
				if ( ! empty( $extension_file_glob ) ) {
779
					include_once $extension_file_glob[0];
780
				}
781
			}
782
		}
783
	}
784
785
	/**
786
	 * Loads PHP components of extended-blocks.
787
	 *
788
	 * @since 8.9.0
789
	 */
790
	public static function load_extended_blocks() {
791
		if ( self::should_load() ) {
792
			$extended_blocks = glob( JETPACK__PLUGIN_DIR . 'extensions/extended-blocks/*' );
793
794
			foreach ( $extended_blocks as $block ) {
795
				$name = basename( $block );
796
				$path = JETPACK__PLUGIN_DIR . 'extensions/extended-blocks/' . $name . '/' . $name . '.php';
797
798
				if ( file_exists( $path ) ) {
799
					include_once $path;
800
				}
801
			}
802
		}
803
	}
804
805
	/**
806
	 * Get CSS classes for a block.
807
	 *
808
	 * @since 7.7.0
809
	 *
810
	 * @param string $slug  Block slug.
811
	 * @param array  $attr  Block attributes.
812
	 * @param array  $extra Potential extra classes you may want to provide.
813
	 *
814
	 * @return string $classes List of CSS classes for a block.
815
	 */
816
	public static function block_classes( $slug, $attr, $extra = array() ) {
817
		_deprecated_function( __METHOD__, '9.0.0', 'Automattic\\Jetpack\\Blocks::classes' );
818
		return Blocks::classes( $slug, $attr, $extra );
819
	}
820
821
	/**
822
	 * Determine whether a site should use the default set of blocks, or a custom set.
823
	 * Possible variations are currently beta, experimental, and production.
824
	 *
825
	 * @since 8.1.0
826
	 *
827
	 * @return string $block_varation production|beta|experimental
828
	 */
829
	public static function blocks_variation() {
830
		// Default to production blocks.
831
		$block_varation = 'production';
832
833
		if ( Constants::is_true( 'JETPACK_BETA_BLOCKS' ) ) {
834
			$block_varation = 'beta';
835
		}
836
837
		/*
838
		 * Switch to experimental blocks if you use the JETPACK_EXPERIMENTAL_BLOCKS constant.
839
		 */
840
		if ( Constants::is_true( 'JETPACK_EXPERIMENTAL_BLOCKS' ) ) {
841
			$block_varation = 'experimental';
842
		}
843
844
		/**
845
		 * Allow customizing the variation of blocks in use on a site.
846
		 *
847
		 * @since 8.1.0
848
		 *
849
		 * @param string $block_variation Can be beta, experimental, and production. Defaults to production.
850
		 */
851
		return apply_filters( 'jetpack_blocks_variation', $block_varation );
852
	}
853
854
	/**
855
	 * Get a list of extensions available for the variation you chose.
856
	 *
857
	 * @since 8.1.0
858
	 *
859
	 * @param obj    $preset_extensions_manifest List of extensions available in Jetpack.
860
	 * @param string $blocks_variation           Subset of blocks. production|beta|experimental.
861
	 *
862
	 * @return array $preset_extensions Array of extensions for that variation
863
	 */
864
	public static function get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation ) {
865
		$preset_extensions = isset( $preset_extensions_manifest->{ $blocks_variation } )
866
				? (array) $preset_extensions_manifest->{ $blocks_variation }
867
				: array();
868
869
		/*
870
		 * Experimental and Beta blocks need the production blocks as well.
871
		 */
872 View Code Duplication
		if (
873
			'experimental' === $blocks_variation
874
			|| 'beta' === $blocks_variation
875
		) {
876
			$production_extensions = isset( $preset_extensions_manifest->production )
877
				? (array) $preset_extensions_manifest->production
878
				: array();
879
880
			$preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
881
		}
882
883
		/*
884
		 * Beta blocks need the experimental blocks as well.
885
		 *
886
		 * If you've chosen to see Beta blocks,
887
		 * we want to make all blocks available to you:
888
		 * - Production
889
		 * - Experimental
890
		 * - Beta
891
		 */
892 View Code Duplication
		if ( 'beta' === $blocks_variation ) {
893
			$production_extensions = isset( $preset_extensions_manifest->experimental )
894
				? (array) $preset_extensions_manifest->experimental
895
				: array();
896
897
			$preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
898
		}
899
900
		return $preset_extensions;
901
	}
902
903
	/**
904
	 * Validate a URL used in a SSR block.
905
	 *
906
	 * @since 8.3.0
907
	 *
908
	 * @param string $url      URL saved as an attribute in block.
909
	 * @param array  $allowed  Array of allowed hosts for that block, or regexes to check against.
910
	 * @param bool   $is_regex Array of regexes matching the URL that could be used in block.
911
	 *
912
	 * @return bool|string
913
	 */
914
	public static function validate_block_embed_url( $url, $allowed = array(), $is_regex = false ) {
915
		if (
916
			empty( $url )
917
			|| ! is_array( $allowed )
918
			|| empty( $allowed )
919
		) {
920
			return false;
921
		}
922
923
		$url_components = wp_parse_url( $url );
924
925
		// Bail early if we cannot find a host.
926
		if ( empty( $url_components['host'] ) ) {
927
			return false;
928
		}
929
930
		// Normalize URL.
931
		$url = sprintf(
932
			'%s://%s%s%s',
933
			isset( $url_components['scheme'] ) ? $url_components['scheme'] : 'https',
934
			$url_components['host'],
935
			isset( $url_components['path'] ) ? $url_components['path'] : '/',
936
			isset( $url_components['query'] ) ? '?' . $url_components['query'] : ''
937
		);
938
939
		if ( ! empty( $url_components['fragment'] ) ) {
940
			$url = $url . '#' . rawurlencode( $url_components['fragment'] );
941
		}
942
943
		/*
944
		 * If we're using an allowed list of hosts,
945
		 * check if the URL belongs to one of the domains allowed for that block.
946
		 */
947
		if (
948
			false === $is_regex
949
			&& in_array( $url_components['host'], $allowed, true )
950
		) {
951
			return $url;
952
		}
953
954
		/*
955
		 * If we are using an array of regexes to check against,
956
		 * loop through that.
957
		 */
958
		if ( true === $is_regex ) {
959
			foreach ( $allowed as $regex ) {
960
				if ( 1 === preg_match( $regex, $url ) ) {
961
					return $url;
962
				}
963
			}
964
		}
965
966
		return false;
967
	}
968
969
	/**
970
	 * Determines whether a preview of the block with an upgrade nudge should
971
	 * be displayed for admins on the site frontend.
972
	 *
973
	 * @since 8.4.0
974
	 *
975
	 * @param array $availability_for_block The availability for the block.
976
	 *
977
	 * @return bool
978
	 */
979
	public static function should_show_frontend_preview( $availability_for_block ) {
980
		return (
981
			isset( $availability_for_block['details']['required_plan'] )
982
			&& current_user_can( 'manage_options' )
983
			&& ! is_feed()
984
		);
985
	}
986
987
	/**
988
	 * Output an UpgradeNudge Component on the frontend of a site.
989
	 *
990
	 * @since 8.4.0
991
	 *
992
	 * @param string $plan The plan that users need to purchase to make the block work.
993
	 *
994
	 * @return string
995
	 */
996
	public static function upgrade_nudge( $plan ) {
997
		jetpack_require_lib( 'components' );
998
		return Jetpack_Components::render_upgrade_nudge(
999
			array(
1000
				'plan' => $plan,
1001
			)
1002
		);
1003
	}
1004
1005
	/**
1006
	 * Output a notice within a block.
1007
	 *
1008
	 * @since 8.6.0
1009
	 *
1010
	 * @param string $message Notice we want to output.
1011
	 * @param string $status  Status of the notice. Can be one of success, info, warning, error. info by default.
1012
	 * @param string $classes List of CSS classes.
1013
	 *
1014
	 * @return string
1015
	 */
1016
	public static function notice( $message, $status = 'info', $classes = '' ) {
1017
		if (
1018
			empty( $message )
1019
			|| ! in_array( $status, array( 'success', 'info', 'warning', 'error' ), true )
1020
		) {
1021
			return '';
1022
		}
1023
1024
		$color = '';
0 ignored issues
show
Unused Code introduced by
$color is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1025
		switch ( $status ) {
1026
			case 'success':
1027
				$color = '#00a32a';
1028
				break;
1029
			case 'warning':
1030
				$color = '#dba617';
1031
				break;
1032
			case 'error':
1033
				$color = '#d63638';
1034
				break;
1035
			case 'info':
1036
			default:
1037
				$color = '#72aee6';
1038
				break;
1039
		}
1040
1041
		return sprintf(
1042
			'<div class="jetpack-block__notice %1$s %3$s" style="border-left:5px solid %4$s;padding:1em;background-color:#f8f9f9;">%2$s</div>',
1043
			esc_attr( $status ),
1044
			wp_kses(
1045
				$message,
1046
				array(
1047
					'br' => array(),
1048
					'p'  => array(),
1049
				)
1050
			),
1051
			esc_attr( $classes ),
1052
			sanitize_hex_color( $color )
1053
		);
1054
	}
1055
1056
	/**
1057
	 * Set the availability of the block as the editor
1058
	 * is loaded.
1059
	 *
1060
	 * @param string $slug Slug of the block.
1061
	 */
1062
	public static function set_availability_for_plan( $slug ) {
1063
		$is_available   = true;
1064
		$plan           = '';
1065
		$slug           = self::remove_extension_prefix( $slug );
1066
		$features_data  = array();
1067
		$is_simple_site = defined( 'IS_WPCOM' ) && IS_WPCOM;
1068
		$is_atomic_site = jetpack_is_atomic_site();
1069
1070
		// Check feature availability for Simple and Atomic sites.
1071
		if ( $is_simple_site || $is_atomic_site ) {
1072
1073
			// Simple sites.
1074
			if ( $is_simple_site ) {
1075
				if ( ! class_exists( 'Store_Product_List' ) ) {
1076
					require WP_CONTENT_DIR . '/admin-plugins/wpcom-billing/store-product-list.php';
1077
				}
1078
				$features_data = Store_Product_List::get_site_specific_features_data();
1079
			} else {
1080
				// Atomic sites.
1081
				$option = get_option( 'jetpack_active_plan' );
1082
				if ( isset( $option['features'] ) ) {
1083
					$features_data = $option['features'];
1084
				}
1085
			}
1086
1087
			$is_available = isset( $features_data['active'] ) && in_array( $slug, $features_data['active'], true );
1088
			if ( ! empty( $features_data['available'][ $slug ] ) ) {
1089
				$plan = $features_data['available'][ $slug ][0];
1090
			}
1091
		} else {
1092
			// Jetpack sites.
1093
			$is_available = Jetpack_Plan::supports( $slug );
1094
			$plan         = Jetpack_Plan::get_minimum_plan_for_feature( $slug );
1095
		}
1096
1097
		if ( $is_available ) {
1098
			self::set_extension_available( $slug );
1099
		} else {
1100
			self::set_extension_unavailable(
1101
				$slug,
1102
				'missing_plan',
1103
				array(
1104
					'required_feature' => $slug,
1105
					'required_plan'    => $plan,
1106
				)
1107
			);
1108
		}
1109
	}
1110
1111
	/**
1112
	 * Wraps the suplied render_callback in a function to check
1113
	 * the availability of the block before rendering it.
1114
	 *
1115
	 * @param string   $slug The block slug, used to check for availability.
1116
	 * @param callable $render_callback The render_callback that will be called if the block is available.
1117
	 */
1118
	public static function get_render_callback_with_availability_check( $slug, $render_callback ) {
1119
		return function ( $prepared_attributes, $block_content, $block ) use ( $render_callback, $slug ) {
1120
			$availability = self::get_cached_availability();
1121
			$bare_slug    = self::remove_extension_prefix( $slug );
1122
			if ( isset( $availability[ $bare_slug ] ) && $availability[ $bare_slug ]['available'] ) {
1123
				return call_user_func( $render_callback, $prepared_attributes, $block_content );
1124
			}
1125
1126
			// A preview of the block is rendered for admins on the frontend with an upgrade nudge.
1127
			if ( isset( $availability[ $bare_slug ] ) ) {
1128
				if ( self::should_show_frontend_preview( $availability[ $bare_slug ] ) ) {
1129
					$block_preview = call_user_func( $render_callback, $prepared_attributes, $block_content );
1130
1131
					// If the upgrade nudge isn't already being displayed by a parent block, display the nudge.
1132
					if ( isset( $block->attributes['shouldDisplayFrontendBanner'] ) && $block->attributes['shouldDisplayFrontendBanner'] ) {
1133
						$upgrade_nudge = self::upgrade_nudge( $availability[ $bare_slug ]['details']['required_plan'] );
1134
						return $upgrade_nudge . $block_preview;
1135
					}
1136
1137
					return $block_preview;
1138
				}
1139
			}
1140
1141
			return null;
1142
		};
1143
	}
1144
}
1145
1146
/*
1147
 * Enable upgrade nudge for Atomic sites.
1148
 * This feature is false as default,
1149
 * so let's enable it through this filter.
1150
 *
1151
 * More doc: https://github.com/Automattic/jetpack/tree/master/projects/plugins/jetpack/extensions#upgrades-for-blocks
1152
 */
1153
if ( jetpack_is_atomic_site() ) {
1154
	add_filter( 'jetpack_block_editor_enable_upgrade_nudge', '__return_true' );
1155
}
1156