Completed
Push — try/package-button-block ( b39073...9065ad )
by
unknown
109:06 queued 101:11
created

Jetpack_Gutenberg::block_has_asset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 3
rs 10
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
	private 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( 'available blocks ' . json_encode( self::$extensions ) );
256
	}
257
258
	/**
259
	 * Resets the class to its original state
260
	 *
261
	 * Used in unit tests
262
	 *
263
	 * @return void
264
	 */
265
	public static function reset() {
266
		self::$extensions   = array();
267
		self::$availability = array();
268
	}
269
270
	/**
271
	 * Return the Gutenberg extensions (blocks and plugins) directory
272
	 *
273
	 * @return string The Gutenberg extensions directory
274
	 */
275
	public static function get_extension_path( $type ) {
276
		/**
277
		 * Filter to select Gutenberg blocks directory
278
		 *
279
		 * @since 6.9.0
280
		 *
281
		 * @param string default: '_inc/blocks/'
282
		 */
283
		$default_directory = apply_filters( 'jetpack_blocks_directory', '_inc/blocks/' );
284
		return apply_filters( 'jetpack_get_extension_path', $default_directory, $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...
285
	}
286
287
	/**
288
	 * Returns a list of Jetpack Gutenberg extensions (blocks and plugins)
289
	 *
290
	 * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
291
	 */
292
	public static function get_jetpack_gutenberg_extensions_allowed_list() {
293
		$preset_extensions_manifest = (object) array();
294
		$blocks_variation           = self::blocks_variation();
295
296
		return self::get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation );
297
	}
298
299
	/**
300
	 * Returns a list of Jetpack Gutenberg extensions (blocks and plugins)
301
	 *
302
	 * @deprecated 8.7.0 Use get_jetpack_gutenberg_extensions_allowed_list()
303
	 *
304
	 * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
305
	 */
306
	public static function get_jetpack_gutenberg_extensions_whitelist() {
307
		_deprecated_function( __FUNCTION__, 'jetpack-8.7.0', 'Jetpack_Gutenberg::get_jetpack_gutenberg_extensions_allowed_list' );
308
		return self::get_jetpack_gutenberg_extensions_allowed_list();
309
	}
310
311
	/**
312
	 * Return true if the extension has been registered and there's nothing in the availablilty array.
313
	 *
314
	 * @param string $extension The name of the extension.
315
	 *
316
	 * @return bool whether the extension has been registered and there's nothing in the availablilty array.
317
	 */
318
	public static function is_registered_and_no_entry_in_availability( $extension ) {
319
		return self::is_registered( 'jetpack/' . $extension ) && ! isset( self::$availability[ $extension ] );
320
	}
321
322
	/**
323
	 * Return true if the extension has a true entry in the availablilty array.
324
	 *
325
	 * @param string $extension The name of the extension.
326
	 *
327
	 * @return bool whether the extension has a true entry in the availablilty array.
328
	 */
329
	public static function is_available( $extension ) {
330
		return isset( self::$availability[ $extension ] ) && true === self::$availability[ $extension ];
331
	}
332
333
	/**
334
	 * Get availability of each block / plugin.
335
	 *
336
	 * @return array A list of block and plugins and their availablity status
337
	 */
338
	public static function get_availability() {
339
		/**
340
		 * Fires before Gutenberg extensions availability is computed.
341
		 *
342
		 * In the function call you supply, use `jetpack_register_block()` to set a block as available.
343
		 * Alternatively, use `Jetpack_Gutenberg::set_extension_available()` (for a non-block plugin), and
344
		 * `Jetpack_Gutenberg::set_extension_unavailable()` (if the block or plugin should not be registered
345
		 * but marked as unavailable).
346
		 *
347
		 * @since 7.0.0
348
		 */
349
		do_action( 'jetpack_register_gutenberg_extensions' );
350
351
		$available_extensions = array();
352
353
		foreach ( self::$extensions as $extension ) {
354
			$is_available                       = self::is_registered_and_no_entry_in_availability( $extension ) || self::is_available( $extension );
355
			$available_extensions[ $extension ] = array(
356
				'available' => $is_available,
357
			);
358
359
			if ( ! $is_available ) {
360
				$reason  = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['reason'] : 'missing_module';
361
				$details = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['details'] : array();
362
				$available_extensions[ $extension ]['unavailable_reason'] = $reason;
363
				$available_extensions[ $extension ]['details']            = $details;
364
			}
365
		}
366
367
		return $available_extensions;
368
	}
369
370
	/**
371
	 * Check if an extension/block is already registered
372
	 *
373
	 * @since 7.2
374
	 *
375
	 * @param string $slug Name of extension/block to check.
376
	 *
377
	 * @return bool
378
	 */
379
	public static function is_registered( $slug ) {
380
		return WP_Block_Type_Registry::get_instance()->is_registered( $slug );
381
	}
382
383
	/**
384
	 * Check if Gutenberg editor is available
385
	 *
386
	 * @since 6.7.0
387
	 *
388
	 * @return bool
389
	 */
390
	public static function is_gutenberg_available() {
391
		return true;
392
	}
393
394
	/**
395
	 * Check whether conditions indicate Gutenberg Extensions (blocks and plugins) should be loaded
396
	 *
397
	 * Loading blocks and plugins is enabled by default and may be disabled via filter:
398
	 *   add_filter( 'jetpack_gutenberg', '__return_false' );
399
	 *
400
	 * @since 6.9.0
401
	 *
402
	 * @return bool
403
	 */
404
	public static function should_load() {
405
		if ( ! Jetpack::is_active() && ! ( new Status() )->is_development_mode() ) {
406
			return false;
407
		}
408
409
		/**
410
		 * Filter to disable Gutenberg blocks
411
		 *
412
		 * @since 6.5.0
413
		 *
414
		 * @param bool true Whether to load Gutenberg blocks
415
		 */
416
		return (bool) apply_filters( 'jetpack_gutenberg', true );
417
	}
418
419
	/**
420
	 * Only enqueue block assets when needed.
421
	 *
422
	 * @param string $type Slug of the block.
423
	 * @param array  $script_dependencies Script dependencies. Will be merged with automatically
424
	 *                                    detected script dependencies from the webpack build.
425
	 *
426
	 * @return void
427
	 */
428
	public static function load_assets_as_required( $type, $script_dependencies = array() ) {
429
		if ( is_admin() ) {
430
			// A block's view assets will not be required in wp-admin.
431
			return;
432
		}
433
434
		$type = sanitize_title_with_dashes( $type );
435
		self::load_styles_as_required( $type );
436
		self::load_scripts_as_required( $type, $script_dependencies );
437
	}
438
439
	/**
440
	 * Only enqueue block sytles when needed.
441
	 *
442
	 * @param string $type Slug of the block.
443
	 *
444
	 * @since 7.2.0
445
	 *
446
	 * @return void
447
	 */
448
	public static function load_styles_as_required( $type ) {
449
		if ( is_admin() ) {
450
			// A block's view assets will not be required in wp-admin.
451
			return;
452
		}
453
454
		// Enqueue styles.
455
		$style_relative_path = self::get_extension_path( $type ) . '/view' . ( is_rtl() ? '.rtl' : '' ) . '.css';
456
		if ( file_exists( JETPACK__PLUGIN_DIR . $style_relative_path ) ) {
457
			$style_version = self::get_asset_version( $style_relative_path );
458
			$view_style    = plugins_url( $style_relative_path, JETPACK__PLUGIN_FILE );
459
			wp_enqueue_style( 'jetpack-block-' . $type, $view_style, array(), $style_version );
460
		}
461
	}
462
463
	/**
464
	 * Only enqueue block scripts when needed.
465
	 *
466
	 * @param string $type Slug of the block.
467
	 * @param array  $script_dependencies Script dependencies. Will be merged with automatically
468
	 *                             detected script dependencies from the webpack build.
469
	 *
470
	 * @since 7.2.0
471
	 *
472
	 * @return void
473
	 */
474
	public static function load_scripts_as_required( $type, $script_dependencies = array() ) {
475
		if ( is_admin() ) {
476
			// A block's view assets will not be required in wp-admin.
477
			return;
478
		}
479
480
		// Enqueue script.
481
		$extension_path        = self::get_extension_path( $type );
482
		$script_relative_path  = $extension_path . '/view.js';
483
		$script_deps_path      = JETPACK__PLUGIN_DIR . $extension_path . '/view.asset.php';
484
		$script_dependencies[] = 'wp-polyfill';
485
		if ( file_exists( $script_deps_path ) ) {
486
			$asset_manifest      = include $script_deps_path;
487
			$script_dependencies = array_unique( array_merge( $script_dependencies, $asset_manifest['dependencies'] ) );
488
		}
489
490
		if ( ( ! class_exists( 'Jetpack_AMP_Support' ) || ! Jetpack_AMP_Support::is_amp_request() ) && file_exists( JETPACK__PLUGIN_DIR . $script_relative_path ) ) {
491
			$script_version = self::get_asset_version( $script_relative_path );
492
			$view_script    = plugins_url( $script_relative_path, JETPACK__PLUGIN_FILE );
493
			wp_enqueue_script( 'jetpack-block-' . $type, $view_script, $script_dependencies, $script_version, false );
494
		}
495
	}
496
497
	/**
498
	 * Get the version number to use when loading the file. Allows us to bypass cache when developing.
499
	 *
500
	 * @param string $file Path of the file we are looking for.
501
	 *
502
	 * @return string $script_version Version number.
503
	 */
504
	public static function get_asset_version( $file ) {
505
		return Jetpack::is_development_version() && file_exists( JETPACK__PLUGIN_DIR . $file )
506
			? filemtime( JETPACK__PLUGIN_DIR . $file )
507
			: JETPACK__VERSION;
508
	}
509
510
	/**
511
	 * Load Gutenberg editor assets
512
	 *
513
	 * @since 6.7.0
514
	 *
515
	 * @return void
516
	 */
517
	public static function enqueue_block_editor_assets() {
518
		if ( ! self::should_load() ) {
519
			return;
520
		}
521
522
		// Required for Analytics. See _inc/lib/admin-pages/class.jetpack-admin-page.php.
523
		if ( ! ( new Status() )->is_development_mode() && Jetpack::is_active() ) {
524
			wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
525
		}
526
527
		$rtl              = is_rtl() ? '.rtl' : '';
528
		$blocks_dir       = self::get_blocks_directory();
0 ignored issues
show
Bug introduced by
The method get_blocks_directory() does not seem to exist on object<Jetpack_Gutenberg>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
529
		$blocks_variation = self::blocks_variation();
530
531
		if ( 'production' !== $blocks_variation ) {
532
			$blocks_env = '-' . esc_attr( $blocks_variation );
533
		} else {
534
			$blocks_env = '';
535
		}
536
537
		$editor_script = plugins_url( "{$blocks_dir}editor{$blocks_env}.js", JETPACK__PLUGIN_FILE );
538
		$editor_style  = plugins_url( "{$blocks_dir}editor{$blocks_env}{$rtl}.css", JETPACK__PLUGIN_FILE );
539
540
		$editor_deps_path = JETPACK__PLUGIN_DIR . $blocks_dir . "editor{$blocks_env}.asset.php";
541
		$editor_deps      = array( 'wp-polyfill' );
542
		if ( file_exists( $editor_deps_path ) ) {
543
			$asset_manifest = include $editor_deps_path;
544
			$editor_deps    = $asset_manifest['dependencies'];
545
		}
546
547
		$version = Jetpack::is_development_version() && file_exists( JETPACK__PLUGIN_DIR . $blocks_dir . 'editor.js' )
548
			? filemtime( JETPACK__PLUGIN_DIR . $blocks_dir . 'editor.js' )
549
			: JETPACK__VERSION;
550
551
		if ( method_exists( 'Jetpack', 'build_raw_urls' ) ) {
552
			$site_fragment = Jetpack::build_raw_urls( home_url() );
553
		} elseif ( class_exists( 'WPCOM_Masterbar' ) && method_exists( 'WPCOM_Masterbar', 'get_calypso_site_slug' ) ) {
554
			$site_fragment = WPCOM_Masterbar::get_calypso_site_slug( get_current_blog_id() );
555
		} else {
556
			$site_fragment = '';
557
		}
558
559
		wp_enqueue_script(
560
			'jetpack-blocks-editor',
561
			$editor_script,
562
			$editor_deps,
563
			$version,
564
			false
565
		);
566
567
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
568
			$user                      = wp_get_current_user();
569
			$user_data                 = array(
570
				'userid'   => $user->ID,
571
				'username' => $user->user_login,
572
			);
573
			$blog_id                   = get_current_blog_id();
574
			$is_current_user_connected = true;
575
		} else {
576
			$user_data                 = Jetpack_Tracks_Client::get_connected_user_tracks_identity();
577
			$blog_id                   = Jetpack_Options::get_option( 'id', 0 );
578
			$is_current_user_connected = Jetpack::is_user_connected();
579
		}
580
581
		wp_localize_script(
582
			'jetpack-blocks-editor',
583
			'Jetpack_Editor_Initial_State',
584
			array(
585
				'available_blocks' => self::get_availability(),
586
				'jetpack'          => array(
587
					'is_active'                 => Jetpack::is_active(),
588
					'is_current_user_connected' => $is_current_user_connected,
589
				),
590
				'siteFragment'     => $site_fragment,
591
				'tracksUserData'   => $user_data,
592
				'wpcomBlogId'      => $blog_id,
593
				'allowedMimeTypes' => wp_get_mime_types(),
594
			)
595
		);
596
597
		wp_set_script_translations( 'jetpack-blocks-editor', 'jetpack' );
598
599
		wp_enqueue_style( 'jetpack-blocks-editor', $editor_style, array(), $version );
600
	}
601
602
	/**
603
	 * Some blocks do not depend on a specific module,
604
	 * and can consequently be loaded outside of the usual modules.
605
	 * We will look for such modules in the extensions/ directory.
606
	 *
607
	 * @since 7.1.0
608
	 *
609
	 * @deprecated 8.8.0 Blocks should be Jetpack modules and manage their own initialization.
610
	 */
611
	public static function load_independent_blocks() {
612
		if ( self::should_load() ) {
613
			/**
614
			 * Look for files that match our list of available Jetpack Gutenberg extensions (blocks and plugins).
615
			 * If available, load them.
616
			 */
617
			foreach ( self::$extensions as $extension ) {
618
				$extension_file_glob = glob( JETPACK__PLUGIN_DIR . 'extensions/*/' . $extension . '/' . $extension . '.php' );
619
				if ( ! empty( $extension_file_glob ) ) {
620
					include_once $extension_file_glob[0];
621
				}
622
			}
623
		}
624
	}
625
626
	/**
627
	 * Get CSS classes for a block.
628
	 *
629
	 * @since 7.7.0
630
	 *
631
	 * @param string $slug  Block slug.
632
	 * @param array  $attr  Block attributes.
633
	 * @param array  $extra Potential extra classes you may want to provide.
634
	 *
635
	 * @return string $classes List of CSS classes for a block.
636
	 */
637
	public static function block_classes( $slug = '', $attr, $extra = array() ) {
638
		if ( empty( $slug ) ) {
639
			return '';
640
		}
641
642
		// Basic block name class.
643
		$classes = array(
644
			'wp-block-jetpack-' . $slug,
645
		);
646
647
		// Add alignment if provided.
648
		if (
649
			! empty( $attr['align'] )
650
			&& in_array( $attr['align'], array( 'left', 'center', 'right', 'wide', 'full' ), true )
651
		) {
652
			array_push( $classes, 'align' . $attr['align'] );
653
		}
654
655
		// Add custom classes if provided in the block editor.
656
		if ( ! empty( $attr['className'] ) ) {
657
			array_push( $classes, $attr['className'] );
658
		}
659
660
		// Add any extra classes.
661
		if ( is_array( $extra ) && ! empty( $extra ) ) {
662
			$classes = array_merge( $classes, array_filter( $extra ) );
663
		}
664
665
		return implode( ' ', $classes );
666
	}
667
668
	/**
669
	 * Determine whether a site should use the default set of blocks, or a custom set.
670
	 * Possible variations are currently beta, experimental, and production.
671
	 *
672
	 * @since 8.1.0
673
	 *
674
	 * @return string $block_varation production|beta|experimental
675
	 */
676
	public static function blocks_variation() {
677
		// Default to production blocks.
678
		$block_varation = 'production';
679
680
		if ( Constants::is_true( 'JETPACK_BETA_BLOCKS' ) ) {
681
			$block_varation = 'beta';
682
		}
683
684
		/*
685
		 * Switch to experimental blocks if you use the JETPACK_EXPERIMENTAL_BLOCKS constant.
686
		 */
687
		if ( Constants::is_true( 'JETPACK_EXPERIMENTAL_BLOCKS' ) ) {
688
			$block_varation = 'experimental';
689
		}
690
691
		/**
692
		 * Allow customizing the variation of blocks in use on a site.
693
		 *
694
		 * @since 8.1.0
695
		 *
696
		 * @param string $block_variation Can be beta, experimental, and production. Defaults to production.
697
		 */
698
		return apply_filters( 'jetpack_blocks_variation', $block_varation );
699
	}
700
701
	/**
702
	 * Get a list of extensions available for the variation you chose.
703
	 *
704
	 * @since 8.1.0
705
	 *
706
	 * @param obj    $preset_extensions_manifest List of extensions available in Jetpack.
707
	 * @param string $blocks_variation           Subset of blocks. production|beta|experimental.
708
	 *
709
	 * @return array $preset_extensions Array of extensions for that variation
710
	 */
711
	public static function get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation ) {
712
		$preset_extensions = isset( $preset_extensions_manifest->{ $blocks_variation } )
713
				? (array) $preset_extensions_manifest->{ $blocks_variation }
714
				: array();
715
716
		/*
717
		 * Experimental and Beta blocks need the production blocks as well.
718
		 */
719 View Code Duplication
		if (
720
			'experimental' === $blocks_variation
721
			|| 'beta' === $blocks_variation
722
		) {
723
			$production_extensions = isset( $preset_extensions_manifest->production )
724
				? (array) $preset_extensions_manifest->production
725
				: array();
726
727
			$preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
728
		}
729
730
		/*
731
		 * Beta blocks need the experimental blocks as well.
732
		 *
733
		 * If you've chosen to see Beta blocks,
734
		 * we want to make all blocks available to you:
735
		 * - Production
736
		 * - Experimental
737
		 * - Beta
738
		 */
739 View Code Duplication
		if ( 'beta' === $blocks_variation ) {
740
			$production_extensions = isset( $preset_extensions_manifest->experimental )
741
				? (array) $preset_extensions_manifest->experimental
742
				: array();
743
744
			$preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
745
		}
746
747
		return $preset_extensions;
748
	}
749
750
	/**
751
	 * Validate a URL used in a SSR block.
752
	 *
753
	 * @since 8.3.0
754
	 *
755
	 * @param string $url      URL saved as an attribute in block.
756
	 * @param array  $allowed  Array of allowed hosts for that block, or regexes to check against.
757
	 * @param bool   $is_regex Array of regexes matching the URL that could be used in block.
758
	 *
759
	 * @return bool|string
760
	 */
761
	public static function validate_block_embed_url( $url, $allowed = array(), $is_regex = false ) {
762
		if (
763
			empty( $url )
764
			|| ! is_array( $allowed )
765
			|| empty( $allowed )
766
		) {
767
			return false;
768
		}
769
770
		$url_components = wp_parse_url( $url );
771
772
		// Bail early if we cannot find a host.
773
		if ( empty( $url_components['host'] ) ) {
774
			return false;
775
		}
776
777
		// Normalize URL.
778
		$url = sprintf(
779
			'%s://%s%s%s',
780
			isset( $url_components['scheme'] ) ? $url_components['scheme'] : 'https',
781
			$url_components['host'],
782
			isset( $url_components['path'] ) ? $url_components['path'] : '/',
783
			isset( $url_components['query'] ) ? '?' . $url_components['query'] : ''
784
		);
785
786
		if ( ! empty( $url_components['fragment'] ) ) {
787
			$url = $url . '#' . rawurlencode( $url_components['fragment'] );
788
		}
789
790
		/*
791
		 * If we're using an allowed list of hosts,
792
		 * check if the URL belongs to one of the domains allowed for that block.
793
		 */
794
		if (
795
			false === $is_regex
796
			&& in_array( $url_components['host'], $allowed, true )
797
		) {
798
			return $url;
799
		}
800
801
		/*
802
		 * If we are using an array of regexes to check against,
803
		 * loop through that.
804
		 */
805
		if ( true === $is_regex ) {
806
			foreach ( $allowed as $regex ) {
807
				if ( 1 === preg_match( $regex, $url ) ) {
808
					return $url;
809
				}
810
			}
811
		}
812
813
		return false;
814
	}
815
816
	/**
817
	 * Output an UpgradeNudge Component on the frontend of a site.
818
	 *
819
	 * @since 8.4.0
820
	 *
821
	 * @param string $plan The plan that users need to purchase to make the block work.
822
	 *
823
	 * @return string
824
	 */
825
	public static function upgrade_nudge( $plan ) {
826
		if (
827
			! current_user_can( 'manage_options' )
828
			/** This filter is documented in class.jetpack-gutenberg.php */
829
			|| ! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false )
830
			/** This filter is documented in _inc/lib/admin-pages/class.jetpack-react-page.php */
831
			|| ! apply_filters( 'jetpack_show_promotions', true )
832
			|| is_feed()
833
		) {
834
			return;
835
		}
836
837
		jetpack_require_lib( 'components' );
838
		return Jetpack_Components::render_upgrade_nudge(
839
			array(
840
				'plan' => $plan,
841
			)
842
		);
843
	}
844
845
	/**
846
	 * Output a notice within a block.
847
	 *
848
	 * @since 8.6.0
849
	 *
850
	 * @param string $message Notice we want to output.
851
	 * @param string $status  Status of the notice. Can be one of success, info, warning, error. info by default.
852
	 * @param string $classes List of CSS classes.
853
	 *
854
	 * @return string
855
	 */
856
	public static function notice( $message, $status = 'info', $classes = '' ) {
857
		if (
858
			empty( $message )
859
			|| ! in_array( $status, array( 'success', 'info', 'warning', 'error' ), true )
860
		) {
861
			return '';
862
		}
863
864
		$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...
865
		switch ( $status ) {
866
			case 'success':
867
				$color = '#46b450';
868
				break;
869
			case 'warning':
870
				$color = '#ffb900';
871
				break;
872
			case 'error':
873
				$color = '#dc3232';
874
				break;
875
			case 'info':
876
			default:
877
				$color = '#00a0d2';
878
				break;
879
		}
880
881
		return sprintf(
882
			'<div class="jetpack-block__notice %1$s %3$s" style="border-left:5px solid %4$s;padding:1em;background-color:#f8f9f9;">%2$s</div>',
883
			esc_attr( $status ),
884
			wp_kses(
885
				$message,
886
				array(
887
					'br' => array(),
888
					'p'  => array(),
889
				)
890
			),
891
			esc_attr( $classes ),
892
			sanitize_hex_color( $color )
893
		);
894
	}
895
896
	/**
897
	 * Set the availability of the block as the editor
898
	 * is loaded.
899
	 *
900
	 * @param string $slug Slug of the block.
901
	 */
902
	public static function set_availability_for_plan( $slug ) {
903
		$is_available = true;
904
		$plan         = '';
905
		$slug         = self::remove_extension_prefix( $slug );
906
907
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
908
			if ( ! class_exists( 'Store_Product_List' ) ) {
909
				require WP_CONTENT_DIR . '/admin-plugins/wpcom-billing/store-product-list.php';
910
			}
911
			$features_data = Store_Product_List::get_site_specific_features_data();
912
			$is_available  = in_array( $slug, $features_data['active'], true );
913
			if ( ! empty( $features_data['available'][ $slug ] ) ) {
914
				$plan = $features_data['available'][ $slug ][0];
915
			}
916
		} elseif ( ! jetpack_is_atomic_site() ) {
917
			/*
918
			 * If it's Atomic then assume all features are available
919
			 * otherwise check against the Jetpack plan.
920
			 */
921
			$is_available = Jetpack_Plan::supports( $slug );
922
			$plan         = Jetpack_Plan::get_minimum_plan_for_feature( $slug );
923
		}
924
		if ( $is_available ) {
925
			self::set_extension_available( $slug );
926
		} else {
927
			self::set_extension_unavailable(
928
				$slug,
929
				'missing_plan',
930
				array(
931
					'required_feature' => $slug,
932
					'required_plan'    => $plan,
933
				)
934
			);
935
		}
936
	}
937
938
	/**
939
	 * Wraps the suplied render_callback in a function to check
940
	 * the availability of the block before rendering it.
941
	 *
942
	 * @param string   $slug The block slug, used to check for availability.
943
	 * @param callable $render_callback The render_callback that will be called if the block is available.
944
	 */
945
	public static function get_render_callback_with_availability_check( $slug, $render_callback ) {
946
		return function ( $prepared_attributes, $block_content ) use ( $render_callback, $slug ) {
947
			$availability = self::get_availability();
948
			$bare_slug    = self::remove_extension_prefix( $slug );
949
			if ( isset( $availability[ $bare_slug ] ) && $availability[ $bare_slug ]['available'] ) {
950
				return call_user_func( $render_callback, $prepared_attributes, $block_content );
951
			} elseif ( isset( $availability[ $bare_slug ]['details']['required_plan'] ) ) {
952
				return self::upgrade_nudge( $availability[ $bare_slug ]['details']['required_plan'] );
953
			}
954
955
			return null;
956
		};
957
	}
958
}
959