Completed
Push — fix/15025-map-block-infinite-s... ( 9a8b21...52d6c3 )
by
unknown
63:16 queued 56:01
created

Jetpack_Gutenberg::notice()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
nc 6
nop 3
dl 0
loc 39
rs 8.3626
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 Jetpack
7
 */
8
9
use Automattic\Jetpack\Constants;
10
use Automattic\Jetpack\Status;
11
12
/**
13
 * Wrapper function to safely register a gutenberg block type
14
 *
15
 * @param string $slug Slug of the block.
16
 * @param array  $args Arguments that are passed into register_block_type.
17
 *
18
 * @see register_block_type
19
 *
20
 * @since 6.7.0
21
 *
22
 * @return WP_Block_Type|false The registered block type on success, or false on failure.
23
 */
24
function jetpack_register_block( $slug, $args = array() ) {
25
	if ( 0 !== strpos( $slug, 'jetpack/' ) && ! strpos( $slug, '/' ) ) {
26
		_doing_it_wrong( 'jetpack_register_block', 'Prefix the block with jetpack/ ', '7.1.0' );
27
		$slug = 'jetpack/' . $slug;
28
	}
29
30
	if ( isset( $args['version_requirements'] )
31
		&& ! Jetpack_Gutenberg::is_gutenberg_version_available( $args['version_requirements'], $slug ) ) {
32
		return false;
33
	}
34
35
	// Checking whether block is registered to ensure it isn't registered twice.
36
	if ( Jetpack_Gutenberg::is_registered( $slug ) ) {
37
		return false;
38
	}
39
40
	$feature_name = Jetpack_Gutenberg::remove_extension_prefix( $slug );
41
	// If the block is dynamic, and a Jetpack block, wrap the render_callback to check availability.
42
	if (
43
		isset( $args['plan_check'], $args['render_callback'] )
44
		&& true === $args['plan_check']
45
	) {
46
		$args['render_callback'] = Jetpack_Gutenberg::get_render_callback_with_availability_check( $feature_name, $args['render_callback'] );
47
		$method_name             = 'set_availability_for_plan';
48
	} else {
49
		$method_name = 'set_extension_available';
50
	}
51
52
	add_action(
53
		'jetpack_register_gutenberg_extensions',
54
		function() use ( $feature_name, $method_name ) {
55
			call_user_func( array( 'Jetpack_Gutenberg', $method_name ), $feature_name );
56
		}
57
	);
58
59
	return register_block_type( $slug, $args );
60
}
61
62
/**
63
 * Helper function to register a Jetpack Gutenberg plugin
64
 *
65
 * @deprecated 7.1.0 Use Jetpack_Gutenberg::set_extension_available() instead
66
 *
67
 * @param string $slug Slug of the plugin.
68
 *
69
 * @since 6.9.0
70
 *
71
 * @return void
72
 */
73
function jetpack_register_plugin( $slug ) {
74
	_deprecated_function( __FUNCTION__, '7.1', 'Jetpack_Gutenberg::set_extension_available' );
75
76
	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...
77
}
78
79
/**
80
 * Set the reason why an extension (block or plugin) is unavailable
81
 *
82
 * @deprecated 7.1.0 Use Jetpack_Gutenberg::set_extension_unavailable() instead
83
 *
84
 * @param string $slug Slug of the block.
85
 * @param string $reason A string representation of why the extension is unavailable.
86
 *
87
 * @since 7.0.0
88
 *
89
 * @return void
90
 */
91
function jetpack_set_extension_unavailability_reason( $slug, $reason ) {
92
	_deprecated_function( __FUNCTION__, '7.1', 'Jetpack_Gutenberg::set_extension_unavailable' );
93
94
	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...
95
}
96
97
/**
98
 * General Gutenberg editor specific functionality
99
 */
100
class Jetpack_Gutenberg {
101
102
	/**
103
	 * Only these extensions can be registered. Used to control availability of beta blocks.
104
	 *
105
	 * @var array Extensions whitelist
106
	 */
107
	private static $extensions = array();
108
109
	/**
110
	 * Keeps track of the reasons why a given extension is unavailable.
111
	 *
112
	 * @var array Extensions availability information
113
	 */
114
	private static $availability = array();
115
116
	/**
117
	 * Check to see if a minimum version of Gutenberg is available. Because a Gutenberg version is not available in
118
	 * php if the Gutenberg plugin is not installed, if we know which minimum WP release has the required version we can
119
	 * optionally fall back to that.
120
	 *
121
	 * @param array  $version_requirements An array containing the required Gutenberg version and, if known, the WordPress version that was released with this minimum version.
122
	 * @param string $slug The slug of the block or plugin that has the gutenberg version requirement.
123
	 *
124
	 * @since 8.3.0
125
	 *
126
	 * @return boolean True if the version of gutenberg required by the block or plugin is available.
127
	 */
128
	public static function is_gutenberg_version_available( $version_requirements, $slug ) {
129
		global $wp_version;
130
131
		// Bail if we don't at least have the gutenberg version requirement, the WP version is optional.
132
		if ( empty( $version_requirements['gutenberg'] ) ) {
133
			return false;
134
		}
135
136
		// If running a local dev build of gutenberg plugin GUTENBERG_DEVELOPMENT_MODE is set so assume correct version.
137
		if ( defined( 'GUTENBERG_DEVELOPMENT_MODE' ) && GUTENBERG_DEVELOPMENT_MODE ) {
138
			return true;
139
		}
140
141
		$version_available = false;
142
143
		// If running a production build of the gutenberg plugin then GUTENBERG_VERSION is set, otherwise if WP version
144
		// with required version of Gutenberg is known check that.
145
		if ( defined( 'GUTENBERG_VERSION' ) ) {
146
			$version_available = version_compare( GUTENBERG_VERSION, $version_requirements['gutenberg'], '>=' );
147
		} elseif ( ! empty( $version_requirements['wp'] ) ) {
148
			$version_available = version_compare( $wp_version, $version_requirements['wp'], '>=' );
149
		}
150
151
		if ( ! $version_available ) {
152
			self::set_extension_unavailable(
153
				$slug,
154
				'incorrect_gutenberg_version',
155
				array(
156
					'required_feature' => $slug,
157
					'required_version' => $version_requirements,
158
					'current_version'  => array(
159
						'wp'        => $wp_version,
160
						'gutenberg' => defined( 'GUTENBERG_VERSION' ) ? GUTENBERG_VERSION : null,
161
					),
162
				)
163
			);
164
		}
165
166
		return $version_available;
167
	}
168
169
	/**
170
	 * Prepend the 'jetpack/' prefix to a block name
171
	 *
172
	 * @param string $block_name The block name.
173
	 *
174
	 * @return string The prefixed block name.
175
	 */
176
	private static function prepend_block_prefix( $block_name ) {
177
		return 'jetpack/' . $block_name;
178
	}
179
180
	/**
181
	 * Remove the 'jetpack/' or jetpack-' prefix from an extension name
182
	 *
183
	 * @param string $extension_name The extension name.
184
	 *
185
	 * @return string The unprefixed extension name.
186
	 */
187
	public static function remove_extension_prefix( $extension_name ) {
188
		if ( 0 === strpos( $extension_name, 'jetpack/' ) || 0 === strpos( $extension_name, 'jetpack-' ) ) {
189
			return substr( $extension_name, strlen( 'jetpack/' ) );
190
		}
191
		return $extension_name;
192
	}
193
194
	/**
195
	 * Whether two arrays share at least one item
196
	 *
197
	 * @param array $a An array.
198
	 * @param array $b Another array.
199
	 *
200
	 * @return boolean True if $a and $b share at least one item
201
	 */
202
	protected static function share_items( $a, $b ) {
203
		return count( array_intersect( $a, $b ) ) > 0;
204
	}
205
206
	/**
207
	 * Register a block
208
	 *
209
	 * @deprecated 7.1.0 Use jetpack_register_block() instead
210
	 *
211
	 * @param string $slug Slug of the block.
212
	 * @param array  $args Arguments that are passed into register_block_type().
213
	 */
214
	public static function register_block( $slug, $args ) {
215
		_deprecated_function( __METHOD__, '7.1', 'jetpack_register_block' );
216
217
		jetpack_register_block( 'jetpack/' . $slug, $args );
218
	}
219
220
	/**
221
	 * Register a plugin
222
	 *
223
	 * @deprecated 7.1.0 Use Jetpack_Gutenberg::set_extension_available() instead
224
	 *
225
	 * @param string $slug Slug of the plugin.
226
	 */
227
	public static function register_plugin( $slug ) {
228
		_deprecated_function( __METHOD__, '7.1', 'Jetpack_Gutenberg::set_extension_available' );
229
230
		self::set_extension_available( $slug );
231
	}
232
233
	/**
234
	 * Register a block
235
	 *
236
	 * @deprecated 7.0.0 Use jetpack_register_block() instead
237
	 *
238
	 * @param string $slug Slug of the block.
239
	 * @param array  $args Arguments that are passed into the register_block_type.
240
	 * @param array  $availability array containing if a block is available and the reason when it is not.
241
	 */
242
	public static function register( $slug, $args, $availability ) {
243
		_deprecated_function( __METHOD__, '7.0', 'jetpack_register_block' );
244
245
		if ( isset( $availability['available'] ) && ! $availability['available'] ) {
246
			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...
247
		} else {
248
			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...
249
		}
250
	}
251
252
	/**
253
	 * Set a (non-block) extension as available
254
	 *
255
	 * @param string $slug Slug of the extension.
256
	 */
257
	public static function set_extension_available( $slug ) {
258
		self::$availability[ self::remove_extension_prefix( $slug ) ] = true;
259
	}
260
261
	/**
262
	 * Set the reason why an extension (block or plugin) is unavailable
263
	 *
264
	 * @param string $slug Slug of the extension.
265
	 * @param string $reason A string representation of why the extension is unavailable.
266
	 * @param array  $details A free-form array containing more information on why the extension is unavailable.
267
	 */
268
	public static function set_extension_unavailable( $slug, $reason, $details = array() ) {
269
		if (
270
			// Extensions that require a plan may be eligible for upgrades.
271
			'missing_plan' === $reason
272
			&& (
273
				/**
274
				 * Filter 'jetpack_block_editor_enable_upgrade_nudge' with `true` to enable or `false`
275
				 * to disable paid feature upgrade nudges in the block editor.
276
				 *
277
				 * When this is changed to default to `true`, you should also update `modules/memberships/class-jetpack-memberships.php`
278
				 * See https://github.com/Automattic/jetpack/pull/13394#pullrequestreview-293063378
279
				 *
280
				 * @since 7.7.0
281
				 *
282
				 * @param boolean
283
				 */
284
				! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false )
285
				/** This filter is documented in _inc/lib/admin-pages/class.jetpack-react-page.php */
286
				|| ! apply_filters( 'jetpack_show_promotions', true )
287
			)
288
		) {
289
			// The block editor may apply an upgrade nudge if `missing_plan` is the reason.
290
			// Add a descriptive suffix to disable behavior but provide informative reason.
291
			$reason .= '__nudge_disabled';
292
		}
293
294
		self::$availability[ self::remove_extension_prefix( $slug ) ] = array(
295
			'reason'  => $reason,
296
			'details' => $details,
297
		);
298
	}
299
300
	/**
301
	 * Set the reason why an extension (block or plugin) is unavailable
302
	 *
303
	 * @deprecated 7.1.0 Use set_extension_unavailable() instead
304
	 *
305
	 * @param string $slug Slug of the extension.
306
	 * @param string $reason A string representation of why the extension is unavailable.
307
	 */
308
	public static function set_extension_unavailability_reason( $slug, $reason ) {
309
		_deprecated_function( __METHOD__, '7.1', 'Jetpack_Gutenberg::set_extension_unavailable' );
310
311
		self::set_extension_unavailable( $slug, $reason );
312
	}
313
314
	/**
315
	 * Set up a whitelist of allowed block editor extensions
316
	 *
317
	 * @return void
318
	 */
319
	public static function init() {
320
		if ( ! self::should_load() ) {
321
			return;
322
		}
323
324
		/**
325
		 * Alternative to `JETPACK_BETA_BLOCKS`, set to `true` to load Beta Blocks.
326
		 *
327
		 * @since 6.9.0
328
		 *
329
		 * @param boolean
330
		 */
331
		if ( apply_filters( 'jetpack_load_beta_blocks', false ) ) {
332
			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...
333
		}
334
335
		/**
336
		 * Alternative to `JETPACK_EXPERIMENTAL_BLOCKS`, set to `true` to load Experimental Blocks.
337
		 *
338
		 * @since 8.4.0
339
		 *
340
		 * @param boolean
341
		 */
342
		if ( apply_filters( 'jetpack_load_experimental_blocks', false ) ) {
343
			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...
344
		}
345
346
		/**
347
		 * Filter the whitelist of block editor extensions that are available through Jetpack.
348
		 *
349
		 * @since 7.0.0
350
		 *
351
		 * @param array
352
		 */
353
		self::$extensions = apply_filters( 'jetpack_set_available_extensions', self::get_available_extensions() );
354
355
		/**
356
		 * Filter the whitelist of block editor plugins that are available through Jetpack.
357
		 *
358
		 * @deprecated 7.0.0 Use jetpack_set_available_extensions instead
359
		 *
360
		 * @since 6.8.0
361
		 *
362
		 * @param array
363
		 */
364
		self::$extensions = apply_filters( 'jetpack_set_available_blocks', self::$extensions );
365
366
		/**
367
		 * Filter the whitelist of block editor plugins that are available through Jetpack.
368
		 *
369
		 * @deprecated 7.0.0 Use jetpack_set_available_extensions instead
370
		 *
371
		 * @since 6.9.0
372
		 *
373
		 * @param array
374
		 */
375
		self::$extensions = apply_filters( 'jetpack_set_available_plugins', self::$extensions );
376
	}
377
378
	/**
379
	 * Resets the class to its original state
380
	 *
381
	 * Used in unit tests
382
	 *
383
	 * @return void
384
	 */
385
	public static function reset() {
386
		self::$extensions   = array();
387
		self::$availability = array();
388
	}
389
390
	/**
391
	 * Return the Gutenberg extensions (blocks and plugins) directory
392
	 *
393
	 * @return string The Gutenberg extensions directory
394
	 */
395
	public static function get_blocks_directory() {
396
		/**
397
		 * Filter to select Gutenberg blocks directory
398
		 *
399
		 * @since 6.9.0
400
		 *
401
		 * @param string default: '_inc/blocks/'
402
		 */
403
		return apply_filters( 'jetpack_blocks_directory', '_inc/blocks/' );
404
	}
405
406
	/**
407
	 * Checks for a given .json file in the blocks folder.
408
	 *
409
	 * @param string $preset The name of the .json file to look for.
410
	 *
411
	 * @return bool True if the file is found.
412
	 */
413
	public static function preset_exists( $preset ) {
414
		return file_exists( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' );
415
	}
416
417
	/**
418
	 * Decodes JSON loaded from a preset file in the blocks folder
419
	 *
420
	 * @param string $preset The name of the .json file to load.
421
	 *
422
	 * @return mixed Returns an object if the file is present, or false if a valid .json file is not present.
423
	 */
424
	public static function get_preset( $preset ) {
425
		return json_decode(
426
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
427
			file_get_contents( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' )
428
		);
429
	}
430
431
	/**
432
	 * Returns a whitelist of Jetpack Gutenberg extensions (blocks and plugins), based on index.json
433
	 *
434
	 * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
435
	 */
436
	public static function get_jetpack_gutenberg_extensions_whitelist() {
437
		$preset_extensions_manifest = self::preset_exists( 'index' )
438
			? self::get_preset( 'index' )
439
			: (object) array();
440
		$blocks_variation           = self::blocks_variation();
441
442
		return self::get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation );
443
	}
444
445
	/**
446
	 * Returns a diff from a combined list of whitelisted extensions and extensions determined to be excluded
447
	 *
448
	 * @param  array $whitelisted_extensions An array of whitelisted extensions.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $whitelisted_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...
449
	 *
450
	 * @return array A list of blocks: eg array( 'publicize', 'markdown' )
451
	 */
452
	public static function get_available_extensions( $whitelisted_extensions = null ) {
453
		$exclusions             = get_option( 'jetpack_excluded_extensions', array() );
454
		$whitelisted_extensions = is_null( $whitelisted_extensions ) ? self::get_jetpack_gutenberg_extensions_whitelist() : $whitelisted_extensions;
455
456
		return array_diff( $whitelisted_extensions, $exclusions );
457
	}
458
459
	/**
460
	 * Return true if the extension has been registered and there's nothing in the availablilty array.
461
	 *
462
	 * @param string $extension The name of the extension.
463
	 *
464
	 * @return bool whether the extension has been registered and there's nothing in the availablilty array.
465
	 */
466
	public static function is_registered_and_no_entry_in_availability( $extension ) {
467
		return self::is_registered( 'jetpack/' . $extension ) && ! isset( self::$availability[ $extension ] );
468
	}
469
470
	/**
471
	 * Return true if the extension has a true entry in the availablilty array.
472
	 *
473
	 * @param string $extension The name of the extension.
474
	 *
475
	 * @return bool whether the extension has a true entry in the availablilty array.
476
	 */
477
	public static function is_available( $extension ) {
478
		return isset( self::$availability[ $extension ] ) && true === self::$availability[ $extension ];
479
	}
480
481
	/**
482
	 * Get availability of each block / plugin.
483
	 *
484
	 * @return array A list of block and plugins and their availablity status
485
	 */
486
	public static function get_availability() {
487
		/**
488
		 * Fires before Gutenberg extensions availability is computed.
489
		 *
490
		 * In the function call you supply, use `jetpack_register_block()` to set a block as available.
491
		 * Alternatively, use `Jetpack_Gutenberg::set_extension_available()` (for a non-block plugin), and
492
		 * `Jetpack_Gutenberg::set_extension_unavailable()` (if the block or plugin should not be registered
493
		 * but marked as unavailable).
494
		 *
495
		 * @since 7.0.0
496
		 */
497
		do_action( 'jetpack_register_gutenberg_extensions' );
498
499
		$available_extensions = array();
500
501
		foreach ( self::$extensions as $extension ) {
502
			$is_available                       = self::is_registered_and_no_entry_in_availability( $extension ) || self::is_available( $extension );
503
			$available_extensions[ $extension ] = array(
504
				'available' => $is_available,
505
			);
506
507
			if ( ! $is_available ) {
508
				$reason  = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['reason'] : 'missing_module';
509
				$details = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['details'] : array();
510
				$available_extensions[ $extension ]['unavailable_reason'] = $reason;
511
				$available_extensions[ $extension ]['details']            = $details;
512
			}
513
		}
514
515
		return $available_extensions;
516
	}
517
518
	/**
519
	 * Check if an extension/block is already registered
520
	 *
521
	 * @since 7.2
522
	 *
523
	 * @param string $slug Name of extension/block to check.
524
	 *
525
	 * @return bool
526
	 */
527
	public static function is_registered( $slug ) {
528
		return WP_Block_Type_Registry::get_instance()->is_registered( $slug );
529
	}
530
531
	/**
532
	 * Check if Gutenberg editor is available
533
	 *
534
	 * @since 6.7.0
535
	 *
536
	 * @return bool
537
	 */
538
	public static function is_gutenberg_available() {
539
		return true;
540
	}
541
542
	/**
543
	 * Check whether conditions indicate Gutenberg Extensions (blocks and plugins) should be loaded
544
	 *
545
	 * Loading blocks and plugins is enabled by default and may be disabled via filter:
546
	 *   add_filter( 'jetpack_gutenberg', '__return_false' );
547
	 *
548
	 * @since 6.9.0
549
	 *
550
	 * @return bool
551
	 */
552
	public static function should_load() {
553
		if ( ! Jetpack::is_active() && ! ( new Status() )->is_development_mode() ) {
554
			return false;
555
		}
556
557
		/**
558
		 * Filter to disable Gutenberg blocks
559
		 *
560
		 * @since 6.5.0
561
		 *
562
		 * @param bool true Whether to load Gutenberg blocks
563
		 */
564
		return (bool) apply_filters( 'jetpack_gutenberg', true );
565
	}
566
567
	/**
568
	 * Only enqueue block assets when needed.
569
	 *
570
	 * @param string $type Slug of the block.
571
	 * @param array  $script_dependencies Script dependencies. Will be merged with automatically
572
	 *                                    detected script dependencies from the webpack build.
573
	 *
574
	 * @return void
575
	 */
576
	public static function load_assets_as_required( $type, $script_dependencies = array() ) {
577
		if ( is_admin() ) {
578
			// A block's view assets will not be required in wp-admin.
579
			return;
580
		}
581
582
		$type = sanitize_title_with_dashes( $type );
583
		self::load_styles_as_required( $type );
584
		self::load_scripts_as_required( $type, $script_dependencies );
585
	}
586
587
	/**
588
	 * Only enqueue block sytles when needed.
589
	 *
590
	 * @param string $type Slug of the block.
591
	 *
592
	 * @since 7.2.0
593
	 *
594
	 * @return void
595
	 */
596
	public static function load_styles_as_required( $type ) {
597
		if ( is_admin() ) {
598
			// A block's view assets will not be required in wp-admin.
599
			return;
600
		}
601
602
		// Enqueue styles.
603
		$style_relative_path = self::get_blocks_directory() . $type . '/view' . ( is_rtl() ? '.rtl' : '' ) . '.css';
604
		if ( self::block_has_asset( $style_relative_path ) ) {
605
			$style_version = self::get_asset_version( $style_relative_path );
606
			$view_style    = plugins_url( $style_relative_path, JETPACK__PLUGIN_FILE );
607
			wp_enqueue_style( 'jetpack-block-' . $type, $view_style, array(), $style_version );
608
		}
609
610
	}
611
612
	/**
613
	 * Only enqueue block scripts when needed.
614
	 *
615
	 * @param string $type Slug of the block.
616
	 * @param array  $script_dependencies Script dependencies. Will be merged with automatically
617
	 *                             detected script dependencies from the webpack build.
618
	 *
619
	 * @since 7.2.0
620
	 *
621
	 * @return void
622
	 */
623
	public static function load_scripts_as_required( $type, $script_dependencies = array() ) {
624
		if ( is_admin() ) {
625
			// A block's view assets will not be required in wp-admin.
626
			return;
627
		}
628
629
		// Enqueue script.
630
		$script_relative_path  = self::get_blocks_directory() . $type . '/view.js';
631
		$script_deps_path      = JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $type . '/view.asset.php';
632
		$script_dependencies[] = 'wp-polyfill';
633
		if ( file_exists( $script_deps_path ) ) {
634
			$asset_manifest      = include $script_deps_path;
635
			$script_dependencies = array_unique( array_merge( $script_dependencies, $asset_manifest['dependencies'] ) );
636
		}
637
638
		if ( ( ! class_exists( 'Jetpack_AMP_Support' ) || ! Jetpack_AMP_Support::is_amp_request() ) && self::block_has_asset( $script_relative_path ) ) {
639
			$script_version = self::get_asset_version( $script_relative_path );
640
			$view_script    = plugins_url( $script_relative_path, JETPACK__PLUGIN_FILE );
641
			wp_enqueue_script( 'jetpack-block-' . $type, $view_script, $script_dependencies, $script_version, false );
642
		}
643
644
		wp_localize_script(
645
			'jetpack-block-' . $type,
646
			'Jetpack_Block_Assets_Base_Url',
647
			plugins_url( self::get_blocks_directory(), JETPACK__PLUGIN_FILE )
648
		);
649
	}
650
651
	/**
652
	 * Check if an asset exists for a block.
653
	 *
654
	 * @param string $file Path of the file we are looking for.
655
	 *
656
	 * @return bool $block_has_asset Does the file exist.
657
	 */
658
	public static function block_has_asset( $file ) {
659
		return file_exists( JETPACK__PLUGIN_DIR . $file );
660
	}
661
662
	/**
663
	 * Get the version number to use when loading the file. Allows us to bypass cache when developing.
664
	 *
665
	 * @param string $file Path of the file we are looking for.
666
	 *
667
	 * @return string $script_version Version number.
668
	 */
669
	public static function get_asset_version( $file ) {
670
		return Jetpack::is_development_version() && self::block_has_asset( $file )
671
			? filemtime( JETPACK__PLUGIN_DIR . $file )
672
			: JETPACK__VERSION;
673
	}
674
675
	/**
676
	 * Load Gutenberg editor assets
677
	 *
678
	 * @since 6.7.0
679
	 *
680
	 * @return void
681
	 */
682
	public static function enqueue_block_editor_assets() {
683
		if ( ! self::should_load() ) {
684
			return;
685
		}
686
687
		// Required for Analytics. See _inc/lib/admin-pages/class.jetpack-admin-page.php.
688
		if ( ! ( new Status() )->is_development_mode() && Jetpack::is_active() ) {
689
			wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
690
		}
691
692
		$rtl              = is_rtl() ? '.rtl' : '';
693
		$blocks_dir       = self::get_blocks_directory();
694
		$blocks_variation = self::blocks_variation();
695
696
		if ( 'production' !== $blocks_variation ) {
697
			$blocks_env = '-' . esc_attr( $blocks_variation );
698
		} else {
699
			$blocks_env = '';
700
		}
701
702
		$editor_script = plugins_url( "{$blocks_dir}editor{$blocks_env}.js", JETPACK__PLUGIN_FILE );
703
		$editor_style  = plugins_url( "{$blocks_dir}editor{$blocks_env}{$rtl}.css", JETPACK__PLUGIN_FILE );
704
705
		$editor_deps_path = JETPACK__PLUGIN_DIR . $blocks_dir . "editor{$blocks_env}.asset.php";
706
		$editor_deps      = array( 'wp-polyfill' );
707
		if ( file_exists( $editor_deps_path ) ) {
708
			$asset_manifest = include $editor_deps_path;
709
			$editor_deps    = $asset_manifest['dependencies'];
710
		}
711
712
		$version = Jetpack::is_development_version() && file_exists( JETPACK__PLUGIN_DIR . $blocks_dir . 'editor.js' )
713
			? filemtime( JETPACK__PLUGIN_DIR . $blocks_dir . 'editor.js' )
714
			: JETPACK__VERSION;
715
716
		if ( method_exists( 'Jetpack', 'build_raw_urls' ) ) {
717
			$site_fragment = Jetpack::build_raw_urls( home_url() );
718
		} elseif ( class_exists( 'WPCOM_Masterbar' ) && method_exists( 'WPCOM_Masterbar', 'get_calypso_site_slug' ) ) {
719
			$site_fragment = WPCOM_Masterbar::get_calypso_site_slug( get_current_blog_id() );
720
		} else {
721
			$site_fragment = '';
722
		}
723
724
		wp_enqueue_script(
725
			'jetpack-blocks-editor',
726
			$editor_script,
727
			$editor_deps,
728
			$version,
729
			false
730
		);
731
732
		wp_localize_script(
733
			'jetpack-blocks-editor',
734
			'Jetpack_Block_Assets_Base_Url',
735
			plugins_url( $blocks_dir . '/', JETPACK__PLUGIN_FILE )
736
		);
737
738
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
739
			$user                      = wp_get_current_user();
740
			$user_data                 = array(
741
				'userid'   => $user->ID,
742
				'username' => $user->user_login,
743
			);
744
			$blog_id                   = get_current_blog_id();
745
			$is_current_user_connected = true;
746
		} else {
747
			$user_data                 = Jetpack_Tracks_Client::get_connected_user_tracks_identity();
748
			$blog_id                   = Jetpack_Options::get_option( 'id', 0 );
749
			$is_current_user_connected = Jetpack::is_user_connected();
750
		}
751
752
		wp_localize_script(
753
			'jetpack-blocks-editor',
754
			'Jetpack_Editor_Initial_State',
755
			array(
756
				'available_blocks' => self::get_availability(),
757
				'jetpack'          => array(
758
					'is_active'                 => Jetpack::is_active(),
759
					'is_current_user_connected' => $is_current_user_connected,
760
				),
761
				'siteFragment'     => $site_fragment,
762
				'tracksUserData'   => $user_data,
763
				'wpcomBlogId'      => $blog_id,
764
			)
765
		);
766
767
		wp_set_script_translations( 'jetpack-blocks-editor', 'jetpack' );
768
769
		wp_enqueue_style( 'jetpack-blocks-editor', $editor_style, array(), $version );
770
	}
771
772
	/**
773
	 * Some blocks do not depend on a specific module,
774
	 * and can consequently be loaded outside of the usual modules.
775
	 * We will look for such modules in the extensions/ directory.
776
	 *
777
	 * @since 7.1.0
778
	 */
779
	public static function load_independent_blocks() {
780
		if ( self::should_load() ) {
781
			/**
782
			 * Look for files that match our list of available Jetpack Gutenberg extensions (blocks and plugins).
783
			 * If available, load them.
784
			 */
785
			foreach ( self::$extensions as $extension ) {
786
				$extension_file_glob = glob( JETPACK__PLUGIN_DIR . 'extensions/*/' . $extension . '/' . $extension . '.php' );
787
				if ( ! empty( $extension_file_glob ) ) {
788
					include_once $extension_file_glob[0];
789
				}
790
			}
791
		}
792
	}
793
794
	/**
795
	 * Get CSS classes for a block.
796
	 *
797
	 * @since 7.7.0
798
	 *
799
	 * @param string $slug  Block slug.
800
	 * @param array  $attr  Block attributes.
801
	 * @param array  $extra Potential extra classes you may want to provide.
802
	 *
803
	 * @return string $classes List of CSS classes for a block.
804
	 */
805
	public static function block_classes( $slug = '', $attr, $extra = array() ) {
806
		if ( empty( $slug ) ) {
807
			return '';
808
		}
809
810
		// Basic block name class.
811
		$classes = array(
812
			'wp-block-jetpack-' . $slug,
813
		);
814
815
		// Add alignment if provided.
816
		if (
817
			! empty( $attr['align'] )
818
			&& in_array( $attr['align'], array( 'left', 'center', 'right', 'wide', 'full' ), true )
819
		) {
820
			array_push( $classes, 'align' . $attr['align'] );
821
		}
822
823
		// Add custom classes if provided in the block editor.
824
		if ( ! empty( $attr['className'] ) ) {
825
			array_push( $classes, $attr['className'] );
826
		}
827
828
		// Add any extra classes.
829
		if ( is_array( $extra ) && ! empty( $extra ) ) {
830
			$classes = array_merge( $classes, array_filter( $extra ) );
831
		}
832
833
		return implode( ' ', $classes );
834
	}
835
836
	/**
837
	 * Determine whether a site should use the default set of blocks, or a custom set.
838
	 * Possible variations are currently beta, experimental, and production.
839
	 *
840
	 * @since 8.1.0
841
	 *
842
	 * @return string $block_varation production|beta|experimental
843
	 */
844
	public static function blocks_variation() {
845
		// Default to production blocks.
846
		$block_varation = 'production';
847
848
		if ( Constants::is_true( 'JETPACK_BETA_BLOCKS' ) ) {
849
			$block_varation = 'beta';
850
		}
851
852
		/*
853
		 * Switch to experimental blocks if you use the JETPACK_EXPERIMENTAL_BLOCKS constant.
854
		 */
855
		if ( Constants::is_true( 'JETPACK_EXPERIMENTAL_BLOCKS' ) ) {
856
			$block_varation = 'experimental';
857
		}
858
859
		/**
860
		 * Allow customizing the variation of blocks in use on a site.
861
		 *
862
		 * @since 8.1.0
863
		 *
864
		 * @param string $block_variation Can be beta, experimental, and production. Defaults to production.
865
		 */
866
		return apply_filters( 'jetpack_blocks_variation', $block_varation );
867
	}
868
869
	/**
870
	 * Get a list of extensions available for the variation you chose.
871
	 *
872
	 * @since 8.1.0
873
	 *
874
	 * @param obj    $preset_extensions_manifest List of extensions available in Jetpack.
875
	 * @param string $blocks_variation           Subset of blocks. production|beta|experimental.
876
	 *
877
	 * @return array $preset_extensions Array of extensions for that variation
878
	 */
879
	public static function get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation ) {
880
		$preset_extensions = isset( $preset_extensions_manifest->{ $blocks_variation } )
881
				? (array) $preset_extensions_manifest->{ $blocks_variation }
882
				: array();
883
884
		/*
885
		 * Experimental and Beta blocks need the production blocks as well.
886
		 */
887 View Code Duplication
		if (
888
			'experimental' === $blocks_variation
889
			|| 'beta' === $blocks_variation
890
		) {
891
			$production_extensions = isset( $preset_extensions_manifest->production )
892
				? (array) $preset_extensions_manifest->production
893
				: array();
894
895
			$preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
896
		}
897
898
		/*
899
		 * Beta blocks need the experimental blocks as well.
900
		 *
901
		 * If you've chosen to see Beta blocks,
902
		 * we want to make all blocks available to you:
903
		 * - Production
904
		 * - Experimental
905
		 * - Beta
906
		 */
907 View Code Duplication
		if ( 'beta' === $blocks_variation ) {
908
			$production_extensions = isset( $preset_extensions_manifest->experimental )
909
				? (array) $preset_extensions_manifest->experimental
910
				: array();
911
912
			$preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
913
		}
914
915
		return $preset_extensions;
916
	}
917
918
	/**
919
	 * Validate a URL used in a SSR block.
920
	 *
921
	 * @since 8.3.0
922
	 *
923
	 * @param string $url      URL saved as an attribute in block.
924
	 * @param array  $allowed  Array of allowed hosts for that block, or regexes to check against.
925
	 * @param bool   $is_regex Array of regexes matching the URL that could be used in block.
926
	 *
927
	 * @return bool|string
928
	 */
929
	public static function validate_block_embed_url( $url, $allowed = array(), $is_regex = false ) {
930
		if (
931
			empty( $url )
932
			|| ! is_array( $allowed )
933
			|| empty( $allowed )
934
		) {
935
			return false;
936
		}
937
938
		$url_components = wp_parse_url( $url );
939
940
		// Bail early if we cannot find a host.
941
		if ( empty( $url_components['host'] ) ) {
942
			return false;
943
		}
944
945
		// Normalize URL.
946
		$url = sprintf(
947
			'%s://%s%s%s',
948
			isset( $url_components['scheme'] ) ? $url_components['scheme'] : 'https',
949
			$url_components['host'],
950
			isset( $url_components['path'] ) ? $url_components['path'] : '/',
951
			isset( $url_components['query'] ) ? '?' . $url_components['query'] : ''
952
		);
953
954
		if ( ! empty( $url_components['fragment'] ) ) {
955
			$url = $url . '#' . rawurlencode( $url_components['fragment'] );
956
		}
957
958
		/*
959
		 * If we're using a whitelist of hosts,
960
		 * check if the URL belongs to one of the domains allowed for that block.
961
		 */
962
		if (
963
			false === $is_regex
964
			&& in_array( $url_components['host'], $allowed, true )
965
		) {
966
			return $url;
967
		}
968
969
		/*
970
		 * If we are using an array of regexes to check against,
971
		 * loop through that.
972
		 */
973
		if ( true === $is_regex ) {
974
			foreach ( $allowed as $regex ) {
975
				if ( 1 === preg_match( $regex, $url ) ) {
976
					return $url;
977
				}
978
			}
979
		}
980
981
		return false;
982
	}
983
984
	/**
985
	 * Output an UpgradeNudge Component on the frontend of a site.
986
	 *
987
	 * @since 8.4.0
988
	 *
989
	 * @param string $plan The plan that users need to purchase to make the block work.
990
	 *
991
	 * @return string
992
	 */
993
	public static function upgrade_nudge( $plan ) {
994
		if (
995
			! current_user_can( 'manage_options' )
996
			/** This filter is documented in class.jetpack-gutenberg.php */
997
			|| ! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false )
998
			/** This filter is documented in _inc/lib/admin-pages/class.jetpack-react-page.php */
999
			|| ! apply_filters( 'jetpack_show_promotions', true )
1000
			|| is_feed()
1001
		) {
1002
			return;
1003
		}
1004
1005
		jetpack_require_lib( 'components' );
1006
		return Jetpack_Components::render_upgrade_nudge(
1007
			array(
1008
				'plan' => $plan,
1009
			)
1010
		);
1011
	}
1012
1013
	/**
1014
	 * Output a notice within a block.
1015
	 *
1016
	 * @since 8.6.0
1017
	 *
1018
	 * @param string $message Notice we want to output.
1019
	 * @param string $status  Status of the notice. Can be one of success, info, warning, error. info by default.
1020
	 * @param string $classes List of CSS classes.
1021
	 *
1022
	 * @return string
1023
	 */
1024
	public static function notice( $message, $status = 'info', $classes = '' ) {
1025
		if (
1026
			empty( $message )
1027
			|| ! in_array( $status, array( 'success', 'info', 'warning', 'error' ), true )
1028
		) {
1029
			return '';
1030
		}
1031
1032
		$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...
1033
		switch ( $status ) {
1034
			case 'success':
1035
				$color = '#46b450';
1036
				break;
1037
			case 'warning':
1038
				$color = '#ffb900';
1039
				break;
1040
			case 'error':
1041
				$color = '#dc3232';
1042
				break;
1043
			case 'info':
1044
			default:
1045
				$color = '#00a0d2';
1046
				break;
1047
		}
1048
1049
		return sprintf(
1050
			'<div class="jetpack-block__notice %1$s %3$s" style="border-left:5px solid %4$s;padding:1em;background-color:#f8f9f9;">%2$s</div>',
1051
			esc_attr( $status ),
1052
			wp_kses(
1053
				$message,
1054
				array(
1055
					'br' => array(),
1056
					'p'  => array(),
1057
				)
1058
			),
1059
			esc_attr( $classes ),
1060
			sanitize_hex_color( $color )
1061
		);
1062
	}
1063
1064
	/**
1065
	 * Set the availability of the block as the editor
1066
	 * is loaded.
1067
	 *
1068
	 * @param string $slug Slug of the block.
1069
	 */
1070
	public static function set_availability_for_plan( $slug ) {
1071
		$is_available = true;
1072
		$plan         = '';
1073
		$slug         = self::remove_extension_prefix( $slug );
1074
1075
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1076
			if ( ! class_exists( 'Store_Product_List' ) ) {
1077
				require WP_CONTENT_DIR . '/admin-plugins/wpcom-billing/store-product-list.php';
1078
			}
1079
			$features_data = Store_Product_List::get_site_specific_features_data();
1080
			$is_available  = in_array( $slug, $features_data['active'], true );
1081
			if ( ! empty( $features_data['available'][ $slug ] ) ) {
1082
				$plan = $features_data['available'][ $slug ][0];
1083
			}
1084
		} elseif ( ! jetpack_is_atomic_site() ) {
1085
			/*
1086
			 * If it's Atomic then assume all features are available
1087
			 * otherwise check against the Jetpack plan.
1088
			 */
1089
			$is_available = Jetpack_Plan::supports( $slug );
1090
			$plan         = Jetpack_Plan::get_minimum_plan_for_feature( $slug );
1091
		}
1092
		if ( $is_available ) {
1093
			self::set_extension_available( $slug );
1094
		} else {
1095
			self::set_extension_unavailable(
1096
				$slug,
1097
				'missing_plan',
1098
				array(
1099
					'required_feature' => $slug,
1100
					'required_plan'    => $plan,
1101
				)
1102
			);
1103
		}
1104
	}
1105
1106
	/**
1107
	 * Wraps the suplied render_callback in a function to check
1108
	 * the availability of the block before rendering it.
1109
	 *
1110
	 * @param string   $slug The block slug, used to check for availability.
1111
	 * @param callable $render_callback The render_callback that will be called if the block is available.
1112
	 */
1113
	public static function get_render_callback_with_availability_check( $slug, $render_callback ) {
1114
		return function ( $prepared_attributes, $block_content ) use ( $render_callback, $slug ) {
1115
			$availability = self::get_availability();
1116
			$bare_slug    = self::remove_extension_prefix( $slug );
1117
			if ( isset( $availability[ $bare_slug ] ) && $availability[ $bare_slug ]['available'] ) {
1118
				return call_user_func( $render_callback, $prepared_attributes, $block_content );
1119
			} elseif ( isset( $availability[ $bare_slug ]['details']['required_plan'] ) ) {
1120
				return self::upgrade_nudge( $availability[ $bare_slug ]['details']['required_plan'] );
1121
			}
1122
1123
			return null;
1124
		};
1125
	}
1126
}
1127