Completed
Push — add/videopress-gutenberg-exten... ( 296eaa...5df94e )
by
unknown
06:49
created

Jetpack_Gutenberg::get_availability()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 10
nop 0
dl 0
loc 28
rs 8.8497
c 0
b 0
f 0
1
<?php
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
/**
10
 * Helper function to register a Jetpack Gutenberg block
11
 *
12
 * @param string $slug Slug of the block.
13
 * @param array  $args Arguments that are passed into register_block_type.
14
 *
15
 * @see register_block_type
16
 *
17
 * @since 6.7.0
18
 *
19
 * @return void
20
 */
21
function jetpack_register_block( $slug, $args = array() ) {
22
	Jetpack_Gutenberg::register_block( $slug, $args );
23
}
24
25
/**
26
 * Helper function to register a Jetpack Gutenberg plugin
27
 *
28
 * @param string $slug Slug of the plugin.
29
 *
30
 * @since 6.9.0
31
 *
32
 * @return void
33
 */
34
function jetpack_register_plugin( $slug ) {
35
	Jetpack_Gutenberg::register_plugin( $slug );
36
}
37
38
39
/**
40
 * Helper function to register a Jetpack Gutenberg extension
41
 *
42
 * @param string   $slug              Slug of the extension.
43
 * @param callable $register_callback Callback used to register the extension.
44
 *
45
 * @since 7.0.0
46
 *
47
 * @return void
48
 */
49
function jetpack_register_extension( $slug, $register_callback ) {
50
	Jetpack_Gutenberg::register_extension( $slug, $register_callback );
51
}
52
53
/**
54
 * Set the reason why an extension (block or plugin) is unavailable
55
 *
56
 * @param string $slug Slug of the block.
57
 * @param string $reason A string representation of why the extension is unavailable.
58
 *
59
 * @since 7.0.0
60
 *
61
 * @return void
62
 */
63
function jetpack_set_extension_unavailability_reason( $slug, $reason ) {
64
	Jetpack_Gutenberg::set_extension_unavailability_reason( $slug, $reason );
65
}
66
67
/**
68
 * General Gutenberg editor specific functionality
69
 */
70
class Jetpack_Gutenberg {
71
72
	/**
73
	 * Only these extensions can be registered. Used to control availability of beta blocks.
74
	 *
75
	 * @var array Extensions whitelist
76
	 */
77
	private static $extensions = array();
78
79
	/**
80
	 * Keeps track of the reasons why a given extension is unavailable.
81
	 *
82
	 * @var array Extensions availability information
83
	 */
84
	private static $availability = array();
85
86
	/**
87
	 * Since there is no `register_plugin()` counterpart to `register_block_type()` in Gutenberg,
88
	 * we have to keep track of plugin registration ourselves
89
	 *
90
	 * @var array Plugin registry
91
	 */
92
	private static $registered_plugins = array();
93
94
	/**
95
	 * Keeps track of the generic extensions registered
96
	 *
97
	 * @var array Plugin registry
98
	 */
99
	private static $registered_extensions = array();
100
101
	/**
102
	 * Prepend the 'jetpack/' prefix to a block name
103
	 *
104
	 * @param string $block_name The block name.
105
	 *
106
	 * @return string The prefixed block name.
107
	 */
108
	private static function prepend_block_prefix( $block_name ) {
109
		return 'jetpack/' . $block_name;
110
	}
111
112
	/**
113
	 * Whether two arrays share at least one item
114
	 *
115
	 * @param array $a An array.
116
	 * @param array $b Another array.
117
	 *
118
	 * @return boolean True if $a and $b share at least one item
119
	 */
120
	protected static function share_items( $a, $b ) {
121
		return count( array_intersect( $a, $b ) ) > 0;
122
	}
123
124
	/**
125
	 * Register a block
126
	 *
127
	 * If the block isn't whitelisted, set its unavailability reason instead.
128
	 *
129
	 * @param string $slug Slug of the block.
130
	 * @param array  $args Arguments that are passed into register_block_type().
131
	 */
132
	public static function register_block( $slug, $args ) {
133
		$prefixed_extensions = array_map( array( __CLASS__, 'prepend_block_prefix' ), self::$extensions );
134
135
		// Register the block if it's whitelisted, or if it's a child block, and one of its parents is whitelisted.
136
		if ( in_array( $slug, self::$extensions, true ) || ( isset( $args['parent'] ) && self::share_items( $args['parent'], $prefixed_extensions ) ) ) {
137
			register_block_type( 'jetpack/' . $slug, $args );
138
		} elseif ( ! isset( $args['parent'] ) ) {
139
			// Don't set availability information for child blocks -- we infer it from their parents.
140
			self::set_extension_unavailability_reason( $slug, 'not_whitelisted' );
141
		}
142
	}
143
144
	/**
145
	 * Register a plugin
146
	 *
147
	 * If the plugin isn't whitelisted, set its unavailability reason instead.
148
	 *
149
	 * @param string $slug Slug of the plugin.
150
	 */
151
	public static function register_plugin( $slug ) {
152
		if ( in_array( $slug, self::$extensions, true ) ) {
153
			self::$registered_plugins[] = 'jetpack-' . $slug;
154
		} else {
155
			self::set_extension_unavailability_reason( $slug, 'not_whitelisted' );
156
		}
157
	}
158
159
	/**
160
	 * Register a generic extension
161
	 *
162
	 * If the extension isn't whitelisted, set its unavailability reason instead.
163
	 *
164
	 * @param string   $slug              Slug of the extension.
165
	 * @param callable $register_callback Callback used to register the extension.
166
	 */
167
	public static function register_extension( $slug, $register_callback ) {
168
		if ( in_array( $slug, self::$extensions, true ) ) {
169
			call_user_func( $register_callback );
170
			self::$registered_extensions[] = 'jetpack/' . $slug;
171
		} else {
172
			self::set_extension_unavailability_reason( $slug, 'not_whitelisted' );
173
		}
174
	}
175
176
	/**
177
	 * Register a block
178
	 *
179
	 * @deprecated 7.0.0 Use register_block() instead
180
	 *
181
	 * @param string $slug Slug of the block.
182
	 * @param array  $args Arguments that are passed into the register_block_type.
183
	 * @param array  $availability array containing if a block is available and the reason when it is not.
184
	 */
185
	public static function register( $slug, $args, $availability ) {
186
		if ( isset( $availability['available'] ) && ! $availability['available'] ) {
187
			self::set_extension_unavailability_reason( $slug, $availability['unavailable_reason'] );
188
		} else {
189
			self::register_block( $slug, $args );
190
		}
191
	}
192
193
	/**
194
	 * Set the reason why an extension (block or plugin) is unavailable
195
	 *
196
	 * @param string $slug Slug of the extension.
197
	 * @param string $reason A string representation of why the extension is unavailable.
198
	 */
199
	public static function set_extension_unavailability_reason( $slug, $reason ) {
200
		self::$availability[ $slug ] = $reason;
201
	}
202
203
	/**
204
	 * Set up a whitelist of allowed block editor extensions
205
	 *
206
	 * @return void
207
	 */
208
	public static function init() {
209
		if ( ! self::is_gutenberg_available() ) {
210
			return;
211
		}
212
213
		if ( ! self::should_load() ) {
214
			return;
215
		}
216
217
		/**
218
		 * Alternative to `JETPACK_BETA_BLOCKS`, set to `true` to load Beta Blocks.
219
		 *
220
		 * @since 6.9.0
221
		 *
222
		 * @param boolean
223
		 */
224
		if ( apply_filters( 'jetpack_load_beta_blocks', false ) ) {
225
			Jetpack_Constants::set_constant( 'JETPACK_BETA_BLOCKS', true );
226
		}
227
228
		/**
229
		 * Filter the whitelist of block editor extensions that are available through Jetpack.
230
		 *
231
		 * @since 7.0.0
232
		 *
233
		 * @param array
234
		 */
235
		self::$extensions = apply_filters( 'jetpack_set_available_extensions', self::get_jetpack_gutenberg_extensions_whitelist() );
236
237
		/**
238
		 * Filter the whitelist of block editor plugins that are available through Jetpack.
239
		 *
240
		 * @deprecated 7.0.0 Use jetpack_set_available_extensions instead
241
		 *
242
		 * @since 6.8.0
243
		 *
244
		 * @param array
245
		 */
246
		self::$extensions = apply_filters( 'jetpack_set_available_blocks', self::$extensions );
247
248
		/**
249
		 * Filter the whitelist of block editor plugins that are available through Jetpack.
250
		 *
251
		 * @deprecated 7.0.0 Use jetpack_set_available_extensions instead
252
		 *
253
		 * @since 6.9.0
254
		 *
255
		 * @param array
256
		 */
257
		self::$extensions = apply_filters( 'jetpack_set_available_plugins', self::$extensions );
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
		self::$registered_plugins = array();
271
		self::$registered_extensions = array();
272
	}
273
274
	/**
275
	 * Return the Gutenberg extensions (blocks and plugins) directory
276
	 *
277
	 * @return string The Gutenberg extensions directory
278
	 */
279
	public static function get_blocks_directory() {
280
		/**
281
		 * Filter to select Gutenberg blocks directory
282
		 *
283
		 * @since 6.9.0
284
		 *
285
		 * @param string default: '_inc/blocks/'
286
		 */
287
		return apply_filters( 'jetpack_blocks_directory', '_inc/blocks/' );
288
	}
289
290
	/**
291
	 * Checks for a given .json file in the blocks folder.
292
	 *
293
	 * @param string $preset The name of the .json file to look for.
294
	 *
295
	 * @return bool True if the file is found.
296
	 */
297
	public static function preset_exists( $preset ) {
298
		return file_exists( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' );
299
	}
300
301
	/**
302
	 * Decodes JSON loaded from a preset file in the blocks folder
303
	 *
304
	 * @param string $preset The name of the .json file to load.
305
	 *
306
	 * @return mixed Returns an object if the file is present, or false if a valid .json file is not present.
307
	 */
308
	public static function get_preset( $preset ) {
309
		return json_decode( file_get_contents( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' ) );
310
	}
311
312
	/**
313
	 * Returns a whitelist of Jetpack Gutenberg extensions (blocks and plugins), based on index.json
314
	 *
315
	 * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
316
	 */
317
	public static function get_jetpack_gutenberg_extensions_whitelist() {
318
		$preset_extensions_manifest = self::preset_exists( 'index' ) ? self::get_preset( 'index' ) : (object) array();
319
320
		$preset_extensions = isset( $preset_extensions_manifest->production ) ? (array) $preset_extensions_manifest->production : array();
321
322
		if ( Jetpack_Constants::is_true( 'JETPACK_BETA_BLOCKS' ) ) {
323
			$beta_extensions = isset( $preset_extensions_manifest->beta ) ? (array) $preset_extensions_manifest->beta : array();
324
			return array_unique( array_merge( $preset_extensions, $beta_extensions ) );
325
		}
326
327
		return $preset_extensions;
328
	}
329
330
	/**
331
	 * Get availability of each block / plugin.
332
	 *
333
	 * @return array A list of block and plugins and their availablity status
334
	 */
335
	public static function get_availability() {
336
		$available_extensions = array();
337
338
		foreach ( self::$extensions as $extension ) {
339
			$is_available = WP_Block_Type_Registry::get_instance()->is_registered( 'jetpack/' . $extension ) ||
340
				in_array( 'jetpack-' . $extension, self::$registered_plugins, true ) ||
341
				in_array( 'jetpack/' . $extension, self::$registered_extensions, true );
342
343
			$available_extensions[ $extension ] = array(
344
				'available' => $is_available,
345
			);
346
347
			if ( ! $is_available ) {
348
				$reason = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ] : 'missing_module';
349
				$available_extensions[ $extension ]['unavailable_reason'] = $reason;
350
			}
351
		}
352
353
		$unwhitelisted = array_fill_keys(
354
			array_diff( array_keys( self::$availability ), self::$extensions ),
355
			array(
356
				'available'          => false,
357
				'unavailable_reason' => 'not_whitelisted',
358
			)
359
		);
360
361
		return array_merge( $available_extensions, $unwhitelisted );
362
	}
363
364
	/**
365
	 * Check if Gutenberg editor is available
366
	 *
367
	 * @since 6.7.0
368
	 *
369
	 * @return bool
370
	 */
371
	public static function is_gutenberg_available() {
372
		return function_exists( 'register_block_type' );
373
	}
374
375
	/**
376
	 * Check whether conditions indicate Gutenberg Extensions (blocks and plugins) should be loaded
377
	 *
378
	 * Loading blocks and plugins is enabled by default and may be disabled via filter:
379
	 *   add_filter( 'jetpack_gutenberg', '__return_false' );
380
	 *
381
	 * @since 6.9.0
382
	 *
383
	 * @return bool
384
	 */
385
	public static function should_load() {
386
		if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
387
			return false;
388
		}
389
390
		/**
391
		 * Filter to disable Gutenberg blocks
392
		 *
393
		 * @since 6.5.0
394
		 *
395
		 * @param bool true Whether to load Gutenberg blocks
396
		 */
397
		return (bool) apply_filters( 'jetpack_gutenberg', true );
398
	}
399
400
	/**
401
	 * Only enqueue block assets when needed.
402
	 *
403
	 * @param string $type slug of the block.
404
	 * @param array  $script_dependencies An array of view-side Javascript dependencies to be enqueued.
405
	 *
406
	 * @return void
407
	 */
408
	public static function load_assets_as_required( $type, $script_dependencies = array() ) {
409
		if ( is_admin() ) {
410
			// A block's view assets will not be required in wp-admin.
411
			return;
412
		}
413
414
		$type = sanitize_title_with_dashes( $type );
415
		// Enqueue styles.
416
		$style_relative_path = self::get_blocks_directory() . $type . '/view' . ( is_rtl() ? '.rtl' : '' ) . '.css';
417 View Code Duplication
		if ( self::block_has_asset( $style_relative_path ) ) {
418
			$style_version = self::get_asset_version( $style_relative_path );
419
			$view_style    = plugins_url( $style_relative_path, JETPACK__PLUGIN_FILE );
420
			wp_enqueue_style( 'jetpack-block-' . $type, $view_style, array(), $style_version );
421
		}
422
423
		// Enqueue script.
424
		$script_relative_path = self::get_blocks_directory() . $type . '/view.js';
425 View Code Duplication
		if ( self::block_has_asset( $script_relative_path ) ) {
426
			$script_version = self::get_asset_version( $script_relative_path );
427
			$view_script    = plugins_url( $script_relative_path, JETPACK__PLUGIN_FILE );
428
			wp_enqueue_script( 'jetpack-block-' . $type, $view_script, $script_dependencies, $script_version, false );
429
		}
430
431
		wp_localize_script(
432
			'jetpack-block-' . $type,
433
			'Jetpack_Block_Assets_Base_Url',
434
			plugins_url( self::get_blocks_directory(), JETPACK__PLUGIN_FILE )
435
		);
436
	}
437
438
	/**
439
	 * Check if an asset exists for a block.
440
	 *
441
	 * @param string $file Path of the file we are looking for.
442
	 *
443
	 * @return bool $block_has_asset Does the file exist.
444
	 */
445
	public static function block_has_asset( $file ) {
446
		return file_exists( JETPACK__PLUGIN_DIR . $file );
447
	}
448
449
	/**
450
	 * Get the version number to use when loading the file. Allows us to bypass cache when developing.
451
	 *
452
	 * @param string $file Path of the file we are looking for.
453
	 *
454
	 * @return string $script_version Version number.
455
	 */
456
	public static function get_asset_version( $file ) {
457
		return Jetpack::is_development_version() && self::block_has_asset( $file )
458
			? filemtime( JETPACK__PLUGIN_DIR . $file )
459
			: JETPACK__VERSION;
460
	}
461
462
	/**
463
	 * Load Gutenberg editor assets
464
	 *
465
	 * @since 6.7.0
466
	 *
467
	 * @return void
468
	 */
469
	public static function enqueue_block_editor_assets() {
470
		if ( ! self::should_load() ) {
471
			return;
472
		}
473
474
		$rtl        = is_rtl() ? '.rtl' : '';
475
		$beta       = Jetpack_Constants::is_true( 'JETPACK_BETA_BLOCKS' ) ? '-beta' : '';
476
		$blocks_dir = self::get_blocks_directory();
477
478
		$editor_script = plugins_url( "{$blocks_dir}editor{$beta}.js", JETPACK__PLUGIN_FILE );
479
		$editor_style  = plugins_url( "{$blocks_dir}editor{$beta}{$rtl}.css", JETPACK__PLUGIN_FILE );
480
481
		$version = Jetpack::is_development_version() && file_exists( JETPACK__PLUGIN_DIR . $blocks_dir . 'editor.js' )
482
			? filemtime( JETPACK__PLUGIN_DIR . $blocks_dir . 'editor.js' )
483
			: JETPACK__VERSION;
484
485
		wp_enqueue_script(
486
			'jetpack-blocks-editor',
487
			$editor_script,
488
			array(
489
				'lodash',
490
				'wp-api-fetch',
491
				'wp-blob',
492
				'wp-blocks',
493
				'wp-components',
494
				'wp-compose',
495
				'wp-data',
496
				'wp-date',
497
				'wp-edit-post',
498
				'wp-editor',
499
				'wp-element',
500
				'wp-hooks',
501
				'wp-i18n',
502
				'wp-keycodes',
503
				'wp-plugins',
504
				'wp-rich-text',
505
				'wp-token-list',
506
				'wp-url',
507
			),
508
			$version,
509
			false
510
		);
511
512
		wp_localize_script(
513
			'jetpack-blocks-editor',
514
			'Jetpack_Block_Assets_Base_Url',
515
			plugins_url( $blocks_dir . '/', JETPACK__PLUGIN_FILE )
516
		);
517
518
		wp_localize_script(
519
			'jetpack-blocks-editor',
520
			'Jetpack_Editor_Initial_State',
521
			array(
522
				'available_blocks' => self::get_availability(),
523
				'jetpack'          => array( 'is_active' => Jetpack::is_active() ),
524
			)
525
		);
526
527
		Jetpack::setup_wp_i18n_locale_data();
528
529
		wp_enqueue_style( 'jetpack-blocks-editor', $editor_style, array(), $version );
530
	}
531
}
532