Completed
Push — try/package-button-block ( 89d64d...e0a758 )
by
unknown
30:46 queued 23:14
created

Jetpack_Gutenberg::get_extension_path()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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