Completed
Push — simplify/jetpack-gutenberg-cla... ( 993ace...e63096 )
by Bernhard
08:02
created

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