Completed
Push — try/package-button-block ( 9d9e85...92fe0a )
by
unknown
145:10 queued 137:02
created

Jetpack_Gutenberg::load_independent_blocks()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
nc 4
nop 0
dl 0
loc 14
rs 9.7998
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
 * General Gutenberg editor specific functionality
64
 */
65
class Jetpack_Gutenberg {
66
67
	/**
68
	 * Only these extensions can be registered. Used to control availability of beta blocks.
69
	 *
70
	 * @var array Extensions allowed list.
71
	 */
72
	public static $extensions = array();
73
74
	/**
75
	 * Keeps track of the reasons why a given extension is unavailable.
76
	 *
77
	 * @var array Extensions availability information
78
	 */
79
	private static $availability = array();
80
81
	/**
82
	 * Check to see if a minimum version of Gutenberg is available. Because a Gutenberg version is not available in
83
	 * php if the Gutenberg plugin is not installed, if we know which minimum WP release has the required version we can
84
	 * optionally fall back to that.
85
	 *
86
	 * @param array  $version_requirements An array containing the required Gutenberg version and, if known, the WordPress version that was released with this minimum version.
87
	 * @param string $slug The slug of the block or plugin that has the gutenberg version requirement.
88
	 *
89
	 * @since 8.3.0
90
	 *
91
	 * @return boolean True if the version of gutenberg required by the block or plugin is available.
92
	 */
93
	public static function is_gutenberg_version_available( $version_requirements, $slug ) {
94
		global $wp_version;
95
96
		// Bail if we don't at least have the gutenberg version requirement, the WP version is optional.
97
		if ( empty( $version_requirements['gutenberg'] ) ) {
98
			return false;
99
		}
100
101
		// If running a local dev build of gutenberg plugin GUTENBERG_DEVELOPMENT_MODE is set so assume correct version.
102
		if ( defined( 'GUTENBERG_DEVELOPMENT_MODE' ) && GUTENBERG_DEVELOPMENT_MODE ) {
103
			return true;
104
		}
105
106
		$version_available = false;
107
108
		// If running a production build of the gutenberg plugin then GUTENBERG_VERSION is set, otherwise if WP version
109
		// with required version of Gutenberg is known check that.
110
		if ( defined( 'GUTENBERG_VERSION' ) ) {
111
			$version_available = version_compare( GUTENBERG_VERSION, $version_requirements['gutenberg'], '>=' );
112
		} elseif ( ! empty( $version_requirements['wp'] ) ) {
113
			$version_available = version_compare( $wp_version, $version_requirements['wp'], '>=' );
114
		}
115
116
		if ( ! $version_available ) {
117
			self::set_extension_unavailable(
118
				$slug,
119
				'incorrect_gutenberg_version',
120
				array(
121
					'required_feature' => $slug,
122
					'required_version' => $version_requirements,
123
					'current_version'  => array(
124
						'wp'        => $wp_version,
125
						'gutenberg' => defined( 'GUTENBERG_VERSION' ) ? GUTENBERG_VERSION : null,
126
					),
127
				)
128
			);
129
		}
130
131
		return $version_available;
132
	}
133
134
	/**
135
	 * Remove the 'jetpack/' or jetpack-' prefix from an extension name
136
	 *
137
	 * @param string $extension_name The extension name.
138
	 *
139
	 * @return string The unprefixed extension name.
140
	 */
141
	public static function remove_extension_prefix( $extension_name ) {
142
		if ( 0 === strpos( $extension_name, 'jetpack/' ) || 0 === strpos( $extension_name, 'jetpack-' ) ) {
143
			return substr( $extension_name, strlen( 'jetpack/' ) );
144
		}
145
		return $extension_name;
146
	}
147
148
	/**
149
	 * Whether two arrays share at least one item
150
	 *
151
	 * @param array $a An array.
152
	 * @param array $b Another array.
153
	 *
154
	 * @return boolean True if $a and $b share at least one item
155
	 */
156
	protected static function share_items( $a, $b ) {
157
		return count( array_intersect( $a, $b ) ) > 0;
158
	}
159
160
	/**
161
	 * Set a (non-block) extension as available
162
	 *
163
	 * @param string $slug Slug of the extension.
164
	 */
165
	public static function set_extension_available( $slug ) {
166
		self::$availability[ self::remove_extension_prefix( $slug ) ] = true;
167
	}
168
169
	/**
170
	 * Set the reason why an extension (block or plugin) is unavailable
171
	 *
172
	 * @param string $slug Slug of the extension.
173
	 * @param string $reason A string representation of why the extension is unavailable.
174
	 * @param array  $details A free-form array containing more information on why the extension is unavailable.
175
	 */
176
	public static function set_extension_unavailable( $slug, $reason, $details = array() ) {
177
		if (
178
			// Extensions that require a plan may be eligible for upgrades.
179
			'missing_plan' === $reason
180
			&& (
181
				/**
182
				 * Filter 'jetpack_block_editor_enable_upgrade_nudge' with `true` to enable or `false`
183
				 * to disable paid feature upgrade nudges in the block editor.
184
				 *
185
				 * When this is changed to default to `true`, you should also update `modules/memberships/class-jetpack-memberships.php`
186
				 * See https://github.com/Automattic/jetpack/pull/13394#pullrequestreview-293063378
187
				 *
188
				 * @since 7.7.0
189
				 *
190
				 * @param boolean
191
				 */
192
				! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false )
193
				/** This filter is documented in _inc/lib/admin-pages/class.jetpack-react-page.php */
194
				|| ! apply_filters( 'jetpack_show_promotions', true )
195
			)
196
		) {
197
			// The block editor may apply an upgrade nudge if `missing_plan` is the reason.
198
			// Add a descriptive suffix to disable behavior but provide informative reason.
199
			$reason .= '__nudge_disabled';
200
		}
201
202
		self::$availability[ self::remove_extension_prefix( $slug ) ] = array(
203
			'reason'  => $reason,
204
			'details' => $details,
205
		);
206
	}
207
208
	/**
209
	 * Set up a list of allowed block editor extensions
210
	 *
211
	 * @return void
212
	 */
213
	public static function init() {
214
		if ( ! self::should_load() ) {
215
			return;
216
		}
217
218
		/**
219
		 * Alternative to `JETPACK_BETA_BLOCKS`, set to `true` to load Beta Blocks.
220
		 *
221
		 * @since 6.9.0
222
		 *
223
		 * @param boolean
224
		 */
225
		if ( apply_filters( 'jetpack_load_beta_blocks', false ) ) {
226
			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...
227
		}
228
229
		/**
230
		 * Alternative to `JETPACK_EXPERIMENTAL_BLOCKS`, set to `true` to load Experimental Blocks.
231
		 *
232
		 * @since 8.4.0
233
		 *
234
		 * @param boolean
235
		 */
236
		if ( apply_filters( 'jetpack_load_experimental_blocks', false ) ) {
237
			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...
238
		}
239
240
		/**
241
		 * Filter the list of block editor extensions that are available through Jetpack.
242
		 *
243
		 * @since 7.0.0
244
		 *
245
		 * @param array
246
		 */
247
		self::$extensions = apply_filters( 'jetpack_set_available_extensions', array(), self::blocks_variation() );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with self::blocks_variation().

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
248
249
		// exclude blocks banned using a database option
250
		$exclusions = get_option( 'jetpack_excluded_extensions', false );
251
		if ( is_array( $exclusions ) ) {
252
			self::$extensions = array_diff( self::$extensions, $exclusions );
253
		}
254
255
		error_log(json_encode(self::$extensions));
256
257
		do_action( 'jetpack_after_extensions_init' );
258
	}
259
260
	/**
261
	 * Resets the class to its original state
262
	 *
263
	 * Used in unit tests
264
	 *
265
	 * @return void
266
	 */
267
	public static function reset() {
268
		self::$extensions   = array();
269
		self::$availability = array();
270
	}
271
272
	/**
273
	 * Return the Gutenberg extensions (blocks and plugins) directory
274
	 *
275
	 * @return string The Gutenberg extensions directory
276
	 */
277
	public static function get_extension_path( $type ) {
278
		$default_extension_path = self::get_blocks_directory() . $type;
279
		return apply_filters( 'jetpack_get_extension_path', $default_extension_path, $type );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $type.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
280
	}
281
282
	public static function get_blocks_directory() {
283
		/**
284
		 * Filter to select Gutenberg blocks directory
285
		 *
286
		 * @since 6.9.0
287
		 *
288
		 * @param string default: false
289
		 */
290
		return apply_filters( 'jetpack_blocks_directory', false );
291
	}
292
293
	/**
294
	 * Returns a list of Jetpack Gutenberg extensions (blocks and plugins)
295
	 *
296
	 * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
297
	 */
298
	public static function get_jetpack_gutenberg_extensions_allowed_list() {
299
		$preset_extensions_manifest = (object) array();
300
		$blocks_variation           = self::blocks_variation();
301
302
		return self::get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation );
303
	}
304
305
	/**
306
	 * Returns a list of Jetpack Gutenberg extensions (blocks and plugins)
307
	 *
308
	 * @deprecated 8.7.0 Use get_jetpack_gutenberg_extensions_allowed_list()
309
	 *
310
	 * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
311
	 */
312
	public static function get_jetpack_gutenberg_extensions_whitelist() {
313
		_deprecated_function( __FUNCTION__, 'jetpack-8.7.0', 'Jetpack_Gutenberg::get_jetpack_gutenberg_extensions_allowed_list' );
314
		return self::get_jetpack_gutenberg_extensions_allowed_list();
315
	}
316
317
	/**
318
	 * Return true if the extension has been registered and there's nothing in the availablilty array.
319
	 *
320
	 * @param string $extension The name of the extension.
321
	 *
322
	 * @return bool whether the extension has been registered and there's nothing in the availablilty array.
323
	 */
324
	public static function is_registered_and_no_entry_in_availability( $extension ) {
325
		return self::is_registered( 'jetpack/' . $extension ) && ! isset( self::$availability[ $extension ] );
326
	}
327
328
	/**
329
	 * Return true if the extension has a true entry in the availablilty array.
330
	 *
331
	 * @param string $extension The name of the extension.
332
	 *
333
	 * @return bool whether the extension has a true entry in the availablilty array.
334
	 */
335
	public static function is_available( $extension ) {
336
		return isset( self::$availability[ $extension ] ) && true === self::$availability[ $extension ];
337
	}
338
339
	/**
340
	 * Get availability of each block / plugin.
341
	 *
342
	 * @return array A list of block and plugins and their availablity status
343
	 */
344
	public static function get_availability() {
345
		/**
346
		 * Fires before Gutenberg extensions availability is computed.
347
		 *
348
		 * In the function call you supply, use `jetpack_register_block()` to set a block as available.
349
		 * Alternatively, use `Jetpack_Gutenberg::set_extension_available()` (for a non-block plugin), and
350
		 * `Jetpack_Gutenberg::set_extension_unavailable()` (if the block or plugin should not be registered
351
		 * but marked as unavailable).
352
		 *
353
		 * @since 7.0.0
354
		 */
355
		do_action( 'jetpack_register_gutenberg_extensions' );
356
357
		$available_extensions = array();
358
359
		foreach ( self::$extensions as $extension ) {
360
			$is_available                       = self::is_registered_and_no_entry_in_availability( $extension ) || self::is_available( $extension );
361
			$available_extensions[ $extension ] = array(
362
				'available' => $is_available,
363
			);
364
365
			if ( ! $is_available ) {
366
				$reason  = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['reason'] : 'missing_module';
367
				$details = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['details'] : array();
368
				$available_extensions[ $extension ]['unavailable_reason'] = $reason;
369
				$available_extensions[ $extension ]['details']            = $details;
370
			}
371
		}
372
373
		return $available_extensions;
374
	}
375
376
	/**
377
	 * Check if an extension/block is already registered
378
	 *
379
	 * @since 7.2
380
	 *
381
	 * @param string $slug Name of extension/block to check.
382
	 *
383
	 * @return bool
384
	 */
385
	public static function is_registered( $slug ) {
386
		return WP_Block_Type_Registry::get_instance()->is_registered( $slug );
387
	}
388
389
	/**
390
	 * Check if Gutenberg editor is available
391
	 *
392
	 * @since 6.7.0
393
	 *
394
	 * @return bool
395
	 */
396
	public static function is_gutenberg_available() {
397
		return true;
398
	}
399
400
	/**
401
	 * Check whether conditions indicate Gutenberg Extensions (blocks and plugins) should be loaded
402
	 *
403
	 * Loading blocks and plugins is enabled by default and may be disabled via filter:
404
	 *   add_filter( 'jetpack_gutenberg', '__return_false' );
405
	 *
406
	 * @since 6.9.0
407
	 *
408
	 * @return bool
409
	 */
410
	public static function should_load() {
411
		/**
412
		 * Filter to disable Gutenberg blocks
413
		 *
414
		 * @since 6.5.0
415
		 *
416
		 * @param bool true Whether to load Gutenberg blocks
417
		 */
418
		return (bool) apply_filters( 'jetpack_gutenberg', true );
419
	}
420
421
	/**
422
	 * Only enqueue block assets when needed.
423
	 *
424
	 * @param string $type Slug of the block.
425
	 * @param array  $script_dependencies Script dependencies. Will be merged with automatically
426
	 *                                    detected script dependencies from the webpack build.
427
	 *
428
	 * @return void
429
	 */
430
	public static function load_assets_as_required( $type, $script_dependencies = array() ) {
431
		if ( is_admin() ) {
432
			// A block's view assets will not be required in wp-admin.
433
			return;
434
		}
435
436
		$type = sanitize_title_with_dashes( $type );
437
		self::load_styles_as_required( $type );
438
		self::load_scripts_as_required( $type, $script_dependencies );
439
	}
440
441
	/**
442
	 * Only enqueue block sytles when needed.
443
	 *
444
	 * @param string $type Slug of the block.
445
	 *
446
	 * @since 7.2.0
447
	 *
448
	 * @return void
449
	 */
450
	public static function load_styles_as_required( $type ) {
451
		if ( is_admin() ) {
452
			// A block's view assets will not be required in wp-admin.
453
			return;
454
		}
455
456
		// Enqueue styles.
457
		$style_path = self::get_extension_path( $type ) . '/view' . ( is_rtl() ? '.rtl' : '' ) . '.css';
458
		if ( file_exists( $style_path ) ) {
459
			$style_version = self::get_asset_version( $style_path );
460
			$view_style    = plugins_url( $style_path );
461
			wp_enqueue_style( 'jetpack-block-' . $type, $view_style, array(), $style_version );
462
		}
463
	}
464
465
	/**
466
	 * Only enqueue block scripts when needed.
467
	 *
468
	 * @param string $type Slug of the block.
469
	 * @param array  $script_dependencies Script dependencies. Will be merged with automatically
470
	 *                             detected script dependencies from the webpack build.
471
	 *
472
	 * @since 7.2.0
473
	 *
474
	 * @return void
475
	 */
476
	public static function load_scripts_as_required( $type, $script_dependencies = array() ) {
477
		if ( is_admin() ) {
478
			// A block's view assets will not be required in wp-admin.
479
			return;
480
		}
481
482
		// Enqueue script.
483
		$extension_path        = self::get_extension_path( $type );
484
		$script_path  = $extension_path . '/view.js';
485
		$script_deps_path      = $extension_path . '/view.asset.php';
486
		$script_dependencies[] = 'wp-polyfill';
487
		if ( file_exists( $script_deps_path ) ) {
488
			$asset_manifest      = include $script_deps_path;
489
			$script_dependencies = array_unique( array_merge( $script_dependencies, $asset_manifest['dependencies'] ) );
490
		}
491
492
		if ( ( ! class_exists( 'Jetpack_AMP_Support' ) || ! Jetpack_AMP_Support::is_amp_request() ) && file_exists( $script_path ) ) {
493
			$script_version = self::get_asset_version( $script_path );
494
			$view_script    = plugins_url( $script_path );
495
			wp_enqueue_script( 'jetpack-block-' . $type, $view_script, $script_dependencies, $script_version, false );
496
		}
497
	}
498
499
	/**
500
	 * Get the version number to use when loading the file. Allows us to bypass cache when developing.
501
	 *
502
	 * @param string $file Path of the file we are looking for.
503
	 *
504
	 * @return string $script_version Version number.
505
	 */
506
	public static function get_asset_version( $file ) {
507
		// @todo - remove this reference to JETPACK__VERSION
508
		return Jetpack::is_development_version() && file_exists( $file )
509
			? filemtime( $file )
510
			: ( defined( 'JETPACK__VERSION' ) ? JETPACK__VERSION : 0 );
511
	}
512
513
	/**
514
	 * Get CSS classes for a block.
515
	 *
516
	 * @since 7.7.0
517
	 *
518
	 * @param string $slug  Block slug.
519
	 * @param array  $attr  Block attributes.
520
	 * @param array  $extra Potential extra classes you may want to provide.
521
	 *
522
	 * @return string $classes List of CSS classes for a block.
523
	 */
524
	public static function block_classes( $slug = '', $attr, $extra = array() ) {
525
		if ( empty( $slug ) ) {
526
			return '';
527
		}
528
529
		// Basic block name class.
530
		$classes = array(
531
			'wp-block-jetpack-' . $slug,
532
		);
533
534
		// Add alignment if provided.
535
		if (
536
			! empty( $attr['align'] )
537
			&& in_array( $attr['align'], array( 'left', 'center', 'right', 'wide', 'full' ), true )
538
		) {
539
			array_push( $classes, 'align' . $attr['align'] );
540
		}
541
542
		// Add custom classes if provided in the block editor.
543
		if ( ! empty( $attr['className'] ) ) {
544
			array_push( $classes, $attr['className'] );
545
		}
546
547
		// Add any extra classes.
548
		if ( is_array( $extra ) && ! empty( $extra ) ) {
549
			$classes = array_merge( $classes, array_filter( $extra ) );
550
		}
551
552
		return implode( ' ', $classes );
553
	}
554
555
	/**
556
	 * Determine whether a site should use the default set of blocks, or a custom set.
557
	 * Possible variations are currently beta, experimental, and production.
558
	 *
559
	 * @since 8.1.0
560
	 *
561
	 * @return string $block_varation production|beta|experimental
562
	 */
563
	public static function blocks_variation() {
564
		// Default to production blocks.
565
		$block_varation = 'production';
566
567
		if ( Constants::is_true( 'JETPACK_BETA_BLOCKS' ) ) {
568
			$block_varation = 'beta';
569
		}
570
571
		/*
572
		 * Switch to experimental blocks if you use the JETPACK_EXPERIMENTAL_BLOCKS constant.
573
		 */
574
		if ( Constants::is_true( 'JETPACK_EXPERIMENTAL_BLOCKS' ) ) {
575
			$block_varation = 'experimental';
576
		}
577
578
		/**
579
		 * Allow customizing the variation of blocks in use on a site.
580
		 *
581
		 * @since 8.1.0
582
		 *
583
		 * @param string $block_variation Can be beta, experimental, and production. Defaults to production.
584
		 */
585
		return apply_filters( 'jetpack_blocks_variation', $block_varation );
586
	}
587
588
	/**
589
	 * Get a list of extensions available for the variation you chose.
590
	 *
591
	 * @since 8.1.0
592
	 *
593
	 * @param obj    $preset_extensions_manifest List of extensions available in Jetpack.
594
	 * @param string $blocks_variation           Subset of blocks. production|beta|experimental.
595
	 *
596
	 * @return array $preset_extensions Array of extensions for that variation
597
	 */
598
	public static function get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation ) {
599
		$preset_extensions = isset( $preset_extensions_manifest->{ $blocks_variation } )
600
				? (array) $preset_extensions_manifest->{ $blocks_variation }
601
				: array();
602
603
		/*
604
		 * Experimental and Beta blocks need the production blocks as well.
605
		 */
606 View Code Duplication
		if (
607
			'experimental' === $blocks_variation
608
			|| 'beta' === $blocks_variation
609
		) {
610
			$production_extensions = isset( $preset_extensions_manifest->production )
611
				? (array) $preset_extensions_manifest->production
612
				: array();
613
614
			$preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
615
		}
616
617
		/*
618
		 * Beta blocks need the experimental blocks as well.
619
		 *
620
		 * If you've chosen to see Beta blocks,
621
		 * we want to make all blocks available to you:
622
		 * - Production
623
		 * - Experimental
624
		 * - Beta
625
		 */
626 View Code Duplication
		if ( 'beta' === $blocks_variation ) {
627
			$production_extensions = isset( $preset_extensions_manifest->experimental )
628
				? (array) $preset_extensions_manifest->experimental
629
				: array();
630
631
			$preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
632
		}
633
634
		return $preset_extensions;
635
	}
636
637
	/**
638
	 * Validate a URL used in a SSR block.
639
	 *
640
	 * @since 8.3.0
641
	 *
642
	 * @param string $url      URL saved as an attribute in block.
643
	 * @param array  $allowed  Array of allowed hosts for that block, or regexes to check against.
644
	 * @param bool   $is_regex Array of regexes matching the URL that could be used in block.
645
	 *
646
	 * @return bool|string
647
	 */
648
	public static function validate_block_embed_url( $url, $allowed = array(), $is_regex = false ) {
649
		if (
650
			empty( $url )
651
			|| ! is_array( $allowed )
652
			|| empty( $allowed )
653
		) {
654
			return false;
655
		}
656
657
		$url_components = wp_parse_url( $url );
658
659
		// Bail early if we cannot find a host.
660
		if ( empty( $url_components['host'] ) ) {
661
			return false;
662
		}
663
664
		// Normalize URL.
665
		$url = sprintf(
666
			'%s://%s%s%s',
667
			isset( $url_components['scheme'] ) ? $url_components['scheme'] : 'https',
668
			$url_components['host'],
669
			isset( $url_components['path'] ) ? $url_components['path'] : '/',
670
			isset( $url_components['query'] ) ? '?' . $url_components['query'] : ''
671
		);
672
673
		if ( ! empty( $url_components['fragment'] ) ) {
674
			$url = $url . '#' . rawurlencode( $url_components['fragment'] );
675
		}
676
677
		/*
678
		 * If we're using an allowed list of hosts,
679
		 * check if the URL belongs to one of the domains allowed for that block.
680
		 */
681
		if (
682
			false === $is_regex
683
			&& in_array( $url_components['host'], $allowed, true )
684
		) {
685
			return $url;
686
		}
687
688
		/*
689
		 * If we are using an array of regexes to check against,
690
		 * loop through that.
691
		 */
692
		if ( true === $is_regex ) {
693
			foreach ( $allowed as $regex ) {
694
				if ( 1 === preg_match( $regex, $url ) ) {
695
					return $url;
696
				}
697
			}
698
		}
699
700
		return false;
701
	}
702
703
	/**
704
	 * Output an UpgradeNudge Component on the frontend of a site.
705
	 *
706
	 * @since 8.4.0
707
	 *
708
	 * @param string $plan The plan that users need to purchase to make the block work.
709
	 *
710
	 * @return string
711
	 */
712
	public static function upgrade_nudge( $plan ) {
713
		if (
714
			! current_user_can( 'manage_options' )
715
			/** This filter is documented in class.jetpack-gutenberg.php */
716
			|| ! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false )
717
			/** This filter is documented in _inc/lib/admin-pages/class.jetpack-react-page.php */
718
			|| ! apply_filters( 'jetpack_show_promotions', true )
719
			|| is_feed()
720
		) {
721
			return;
722
		}
723
724
		jetpack_require_lib( 'components' );
725
		return Jetpack_Components::render_upgrade_nudge(
726
			array(
727
				'plan' => $plan,
728
			)
729
		);
730
	}
731
732
	/**
733
	 * Output a notice within a block.
734
	 *
735
	 * @since 8.6.0
736
	 *
737
	 * @param string $message Notice we want to output.
738
	 * @param string $status  Status of the notice. Can be one of success, info, warning, error. info by default.
739
	 * @param string $classes List of CSS classes.
740
	 *
741
	 * @return string
742
	 */
743
	public static function notice( $message, $status = 'info', $classes = '' ) {
744
		if (
745
			empty( $message )
746
			|| ! in_array( $status, array( 'success', 'info', 'warning', 'error' ), true )
747
		) {
748
			return '';
749
		}
750
751
		$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...
752
		switch ( $status ) {
753
			case 'success':
754
				$color = '#46b450';
755
				break;
756
			case 'warning':
757
				$color = '#ffb900';
758
				break;
759
			case 'error':
760
				$color = '#dc3232';
761
				break;
762
			case 'info':
763
			default:
764
				$color = '#00a0d2';
765
				break;
766
		}
767
768
		return sprintf(
769
			'<div class="jetpack-block__notice %1$s %3$s" style="border-left:5px solid %4$s;padding:1em;background-color:#f8f9f9;">%2$s</div>',
770
			esc_attr( $status ),
771
			wp_kses(
772
				$message,
773
				array(
774
					'br' => array(),
775
					'p'  => array(),
776
				)
777
			),
778
			esc_attr( $classes ),
779
			sanitize_hex_color( $color )
780
		);
781
	}
782
783
	/**
784
	 * Set the availability of the block as the editor
785
	 * is loaded.
786
	 *
787
	 * @param string $slug Slug of the block.
788
	 */
789
	public static function set_availability_for_plan( $slug ) {
790
		$is_available = true;
791
		$plan         = '';
792
		$slug         = self::remove_extension_prefix( $slug );
793
794
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
795
			if ( ! class_exists( 'Store_Product_List' ) ) {
796
				require WP_CONTENT_DIR . '/admin-plugins/wpcom-billing/store-product-list.php';
797
			}
798
			$features_data = Store_Product_List::get_site_specific_features_data();
799
			$is_available  = in_array( $slug, $features_data['active'], true );
800
			if ( ! empty( $features_data['available'][ $slug ] ) ) {
801
				$plan = $features_data['available'][ $slug ][0];
802
			}
803
		} elseif ( ! jetpack_is_atomic_site() ) {
804
			/*
805
			 * If it's Atomic then assume all features are available
806
			 * otherwise check against the Jetpack plan.
807
			 */
808
			$is_available = Jetpack_Plan::supports( $slug );
809
			$plan         = Jetpack_Plan::get_minimum_plan_for_feature( $slug );
810
		}
811
		if ( $is_available ) {
812
			self::set_extension_available( $slug );
813
		} else {
814
			self::set_extension_unavailable(
815
				$slug,
816
				'missing_plan',
817
				array(
818
					'required_feature' => $slug,
819
					'required_plan'    => $plan,
820
				)
821
			);
822
		}
823
	}
824
825
	/**
826
	 * Wraps the suplied render_callback in a function to check
827
	 * the availability of the block before rendering it.
828
	 *
829
	 * @param string   $slug The block slug, used to check for availability.
830
	 * @param callable $render_callback The render_callback that will be called if the block is available.
831
	 */
832
	public static function get_render_callback_with_availability_check( $slug, $render_callback ) {
833
		return function ( $prepared_attributes, $block_content ) use ( $render_callback, $slug ) {
834
			$availability = self::get_availability();
835
			$bare_slug    = self::remove_extension_prefix( $slug );
836
			if ( isset( $availability[ $bare_slug ] ) && $availability[ $bare_slug ]['available'] ) {
837
				return call_user_func( $render_callback, $prepared_attributes, $block_content );
838
			} elseif ( isset( $availability[ $bare_slug ]['details']['required_plan'] ) ) {
839
				return self::upgrade_nudge( $availability[ $bare_slug ]['details']['required_plan'] );
840
			}
841
842
			return null;
843
		};
844
	}
845
}
846