PluginProbe ʕ •ᴥ•ʔ
Jetpack – WP Security, Backup, Speed, & Growth / 14.4.2
Jetpack – WP Security, Backup, Speed, & Growth v14.4.2
12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 14.4.2 14.5.1 14.6.1 14.7.1 14.8.1 14.9.2 15.0.3 15.1.2 15.2.1 15.3.2 15.4.1 15.5.1 15.6.1 15.7.2 15.8.1 15.9.2 16.0.2 16.1.3 16.2-a.5 16.2-a.3 16.1.2 16.2-a.1 16.1.1 16.1 16.1-beta 16.1-beta.2 16.1-beta.3 16.1-a.5 16.1-a.3 16.0.1 16.1-a.1 16.0 16.0-beta 16.0-a.7 16.0-a.5 15.9.1 16.0-a.3 16.0-a.1 15.9 15.9-beta 15.9-a.7 15.9-a.5 15.9-a.3 15.9-a.1 15.8 15.8-beta 15.8-a.7 15.8-a.5 5.2.5 5.3.4 5.4.4 5.5.5 5.6.5 5.7.5 5.8.4 5.9.4 6.0.4 6.1 6.1.1 6.1.2 6.1.3 6.1.4 6.1.5 6.2 6.2.1 6.2.2 6.2.3 6.2.4 6.2.5 6.3 6.3.1 6.3.2 6.3.3 6.3.4 6.3.5 6.3.6 6.3.7 6.4 6.4.1 6.4.2 6.4.3 6.4.4 6.4.5 6.4.6 6.5 6.5.1 6.5.2 6.5.3 6.5.4 6.6 6.6.1 6.6.2 6.6.3 6.6.4 6.6.5 6.7 6.7.1 6.7.2 6.7.3 6.7.4 6.8 6.8.1 6.8.2 6.8.3 6.8.4 6.8.5 6.9 6.9.1 6.9.2 6.9.3 6.9.4 7.0 7.0.1 7.0.2 7.0.3 7.0.4 7.0.5 7.1 7.1.1 7.1.2 7.1.3 7.1.4 7.1.5 7.2 7.2.1 7.2.1.1 7.2.2 7.2.3 7.2.4 7.2.5 7.3 7.3.0.1 7.3.1 7.3.1.1 7.3.2 7.3.3 7.3.4 7.3.5 7.4 7.4.1 7.4.2 7.4.3 7.4.4 7.4.5 7.5 7.5.0.1 7.5.1 7.5.2 7.5.3 7.5.4 7.5.5 7.5.6 7.5.7 7.6 7.6.1 7.6.2 7.6.3 7.6.4 7.7 7.7.1 7.7.2 7.7.3 7.7.4 7.7.5 7.7.6 7.8 7.8.1 7.8.2 7.8.3 7.8.4 7.9 7.9.1 7.9.2 7.9.3 7.9.4 8.0 8.0.1 8.0.2 8.0.3 8.1 8.1.1 8.1.2 8.1.3 8.1.4 8.2 8.2.0.1 8.2.1 8.2.2 8.2.3 8.2.4 8.2.5 8.2.6 8.3 8.3.1 8.3.2 8.3.3 8.4 8.4.1 8.4.2 8.4.3 8.4.4 8.4.5 8.5 8.5.1 8.5.2 8.5.3 8.6 8.6.1 8.6.2 8.6.3 8.6.4 8.7 8.7.0.1 8.7.1 8.7.2 8.7.3 8.7.4 8.8 8.8.1 8.8.2 8.8.3 8.8.4 8.8.5 8.9 8.9.1 8.9.2 8.9.3 8.9.4 9.0 9.0.1 9.0.2 9.0.3 9.0.4 9.0.5 9.1 9.1.1 9.1.2 9.1.3 9.2 9.2.1 9.2.2 9.2.3 9.2.4 9.3 9.3.1 9.3.2 9.3.3 9.3.4 9.3.5 9.4 9.4.1 9.4.2 9.4.3 9.4.4 9.5 9.5.1 9.5.2 9.5.3 9.5.4 9.5.5 9.6 9.6.1 9.6.2 9.6.3 9.6.4 9.7 9.7.1 9.7.2 15.7-beta.2 9.7.3 15.7.1 9.8 15.8-a.1 9.8.1 15.8-a.3 9.8.2 2.0.9 9.8.3 2.1.7 9.9 2.2.10 9.9.1 2.3.10 9.9.2 2.4.7 9.9.3 2.5.5 2.6.6 2.7.5 2.8.5 2.9.6 3.0.6 3.1.5 3.2.5 3.3.6 3.4.6 3.5.6 3.6.4 3.7.5 3.8.5 3.9.10 4.0.7 4.1.4 4.2.5 4.3.5 4.4.5 4.5.3 4.6.3 4.7.4 4.8.5 4.9.3 5.0.3 5.1.4 trunk 10.0 10.0.1 10.0.2 10.1 10.1.1 10.1.2 10.2 10.2.1 10.2.2 10.2.3 10.3 10.3.1 10.3.2 10.4 10.4.1 10.4.2 10.5 10.5.1 10.5.2 10.5.3 10.6 10.6.1 10.6.2 10.7 10.7.1 10.7.2 10.8 10.8.1 10.8.2 10.9 10.9.1 10.9.2 10.9.3 11.0 11.0.1 11.0.2 11.1 11.1.1 11.1.2 11.1.3 11.1.4 11.2 11.2.1 11.2.2 11.3 11.3.1 11.3.2 11.3.3 11.3.4 11.4 11.4.1 11.4.2 11.5 11.5.1 11.5.2 11.5.3 11.6 11.6.1 11.6.2 11.7 11.7.1 11.7.2 11.7.3 11.8 11.8.3 11.8.4 11.8.5 11.8.6 11.9 11.9.1 11.9.2 11.9.3 12.0 12.0.1 12.0.2 12.1 12.1.1 12.1.2 12.2 12.2.1 12.2.2 12.3 12.3.1 12.4 12.4.1 12.5 12.5.1 12.6 12.6.1 12.6.2 12.6.3 12.7 12.7.1 12.7.2 12.8 12.8.1 12.8.2 12.9 12.9.1 12.9.2 12.9.3 12.9.4 13.0 13.0.1 13.1 13.1.1 13.1.2 13.1.3 13.1.4 13.2 13.2.1 13.2.2 13.2.3 13.3 13.3.1 13.3.2 13.4 13.4.1 13.4.2 13.4.3 13.4.4 13.5 13.5.1 13.6 13.6.1 13.7 13.7.1 13.8 13.8.1 13.8.2 13.9 13.9.1 14.0 14.1 14.2 14.2.1 14.3 14.4 14.4.1 14.5 14.6 14.7 14.8 14.9 14.9.1 15.0 15.0.1 15.0.2 15.1 15.1.1 15.2 15.3 15.3.1 15.4 15.5 15.6 15.7 15.7-a.1 15.7-a.3 15.7-a.5 15.7-a.7 15.7-beta
jetpack / class.jetpack-gutenberg.php
jetpack Last commit date
3rd-party 1 year ago _inc 1 year ago css 1 year ago extensions 1 year ago images 1 year ago jetpack_vendor 1 day ago json-endpoints 1 year ago modules 1 year ago sal 1 year ago src 1 year ago vendor 1 year ago views 2 years ago CHANGELOG.md 1 year ago LICENSE.txt 5 years ago SECURITY.md 2 years ago class-jetpack-connection-status.php 2 years ago class-jetpack-gallery-settings.php 3 years ago class-jetpack-newsletter-dashboard-widget.php 1 year ago class-jetpack-pre-connection-jitms.php 2 years ago class-jetpack-stats-dashboard-widget.php 1 year ago class-jetpack-xmlrpc-methods.php 1 year ago class.frame-nonce-preview.php 1 year ago class.jetpack-admin.php 1 year ago class.jetpack-affiliate.php 2 years ago class.jetpack-autoupdate.php 2 years ago class.jetpack-bbpress-json-api.compat.php 2 years ago class.jetpack-cli.php 1 year ago class.jetpack-client-server.php 2 years ago class.jetpack-gutenberg.php 1 year ago class.jetpack-heartbeat.php 2 years ago class.jetpack-modules-list-table.php 2 years ago class.jetpack-network-sites-list-table.php 2 years ago class.jetpack-network.php 1 year ago class.jetpack-plan.php 3 years ago class.jetpack-post-images.php 1 year ago class.jetpack-twitter-cards.php 2 years ago class.jetpack-user-agent.php 2 years ago class.jetpack.php 1 year ago class.json-api-endpoints.php 1 year ago class.json-api.php 1 year ago class.photon.php 3 years ago composer.json 1 year ago enhanced-open-graph.php 3 years ago functions.compat.php 2 years ago functions.cookies.php 2 years ago functions.global.php 1 year ago functions.is-mobile.php 2 years ago functions.opengraph.php 1 year ago functions.photon.php 2 years ago global.d.ts 2 years ago jetpack.php 1 day ago json-api-config.php 3 years ago json-endpoints.php 2 years ago load-jetpack.php 2 years ago locales.php 4 years ago readme.txt 1 day ago uninstall.php 1 year ago wpml-config.xml 4 years ago
class.jetpack-gutenberg.php
1391 lines
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 automattic/jetpack
7 */
8
9 use Automattic\Jetpack\Assets;
10 use Automattic\Jetpack\Blocks;
11 use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
12 use Automattic\Jetpack\Connection\Manager as Connection_Manager;
13 use Automattic\Jetpack\Constants;
14 use Automattic\Jetpack\Current_Plan as Jetpack_Plan;
15 use Automattic\Jetpack\Modules;
16 use Automattic\Jetpack\My_Jetpack\Initializer as My_Jetpack_Initializer;
17 use Automattic\Jetpack\Publicize\Jetpack_Social_Settings\Dismissed_Notices;
18 use Automattic\Jetpack\Status;
19 use Automattic\Jetpack\Status\Host;
20
21 // phpcs:disable Universal.Files.SeparateFunctionsFromOO.Mixed -- TODO: Move the functions and such to some other file.
22
23 /**
24 * General Gutenberg editor specific functionality
25 */
26 class Jetpack_Gutenberg {
27
28 /**
29 * Only these extensions can be registered. Used to control availability of beta blocks.
30 *
31 * @var array|null Extensions allowed list or `null` if not initialized yet.
32 * @see static::get_extensions()
33 */
34 private static $extensions = null;
35
36 /**
37 * Keeps track of the reasons why a given extension is unavailable.
38 *
39 * @var array Extensions availability information
40 */
41 private static $availability = array();
42
43 /**
44 * A cached array of the fully processed availability data. Keeps track of
45 * reasons why an extension is unavailable or missing.
46 *
47 * @var array Extensions availability information.
48 */
49 private static $cached_availability = null;
50
51 /**
52 * Site-specific features available.
53 * Their calculation can be expensive and slow, so we're caching it for the request.
54 *
55 * @var array Site-specific features
56 */
57 private static $site_specific_features = array();
58
59 /**
60 * List of deprecated blocks.
61 *
62 * @var array List of deprecated blocks.
63 */
64 private static $deprecated_blocks = array(
65 'jetpack/revue',
66 );
67
68 /**
69 * Storing the contents of the preset file.
70 *
71 * Already been json_decode.
72 *
73 * @var null|object JSON decoded object after first usage.
74 */
75 private static $preset_cache = null;
76
77 /**
78 * Check to see if a minimum version of Gutenberg is available. Because a Gutenberg version is not available in
79 * php if the Gutenberg plugin is not installed, if we know which minimum WP release has the required version we can
80 * optionally fall back to that.
81 *
82 * @param array $version_requirements An array containing the required Gutenberg version and, if known, the WordPress version that was released with this minimum version.
83 * @param string $slug The slug of the block or plugin that has the gutenberg version requirement.
84 *
85 * @since 8.3.0
86 *
87 * @return boolean True if the version of gutenberg required by the block or plugin is available.
88 */
89 public static function is_gutenberg_version_available( $version_requirements, $slug ) {
90 global $wp_version;
91
92 // Bail if we don't at least have the gutenberg version requirement, the WP version is optional.
93 if ( empty( $version_requirements['gutenberg'] ) ) {
94 return false;
95 }
96
97 // If running a local dev build of gutenberg plugin GUTENBERG_DEVELOPMENT_MODE is set so assume correct version.
98 if ( defined( 'GUTENBERG_DEVELOPMENT_MODE' ) && GUTENBERG_DEVELOPMENT_MODE ) {
99 return true;
100 }
101
102 $version_available = false;
103
104 // If running a production build of the gutenberg plugin then GUTENBERG_VERSION is set, otherwise if WP version
105 // with required version of Gutenberg is known check that.
106 if ( defined( 'GUTENBERG_VERSION' ) ) {
107 $version_available = version_compare( GUTENBERG_VERSION, $version_requirements['gutenberg'], '>=' );
108 } elseif ( ! empty( $version_requirements['wp'] ) ) {
109 $version_available = version_compare( $wp_version, $version_requirements['wp'], '>=' );
110 }
111
112 if ( ! $version_available ) {
113 $slug = self::remove_extension_prefix( $slug );
114 self::set_extension_unavailable(
115 $slug,
116 'incorrect_gutenberg_version',
117 array(
118 'required_feature' => $slug,
119 'required_version' => $version_requirements,
120 'current_version' => array(
121 'wp' => $wp_version,
122 'gutenberg' => defined( 'GUTENBERG_VERSION' ) ? GUTENBERG_VERSION : null,
123 ),
124 )
125 );
126 }
127
128 return $version_available;
129 }
130
131 /**
132 * Prepend the 'jetpack/' prefix to a block name
133 *
134 * @param string $block_name The block name.
135 *
136 * @return string The prefixed block name.
137 */
138 private static function prepend_block_prefix( $block_name ) {
139 return 'jetpack/' . $block_name;
140 }
141
142 /**
143 * Remove the 'jetpack/' or jetpack-' prefix from an extension name
144 *
145 * @param string $extension_name The extension name.
146 *
147 * @return string The unprefixed extension name.
148 */
149 public static function remove_extension_prefix( $extension_name ) {
150 if ( str_starts_with( $extension_name, 'jetpack/' ) || str_starts_with( $extension_name, 'jetpack-' ) ) {
151 return substr( $extension_name, strlen( 'jetpack/' ) );
152 }
153 return $extension_name;
154 }
155
156 /**
157 * Whether two arrays share at least one item
158 *
159 * @param array $a An array.
160 * @param array $b Another array.
161 *
162 * @return boolean True if $a and $b share at least one item
163 */
164 protected static function share_items( $a, $b ) {
165 return array_intersect( $a, $b ) !== array();
166 }
167
168 /**
169 * Set a (non-block) extension as available
170 *
171 * @param string $slug Slug of the extension.
172 */
173 public static function set_extension_available( $slug ) {
174 $slug = self::remove_extension_prefix( $slug );
175 self::$availability[ $slug ] = true;
176 }
177
178 /**
179 * Set the reason why an extension (block or plugin) is unavailable
180 *
181 * @param string $slug Slug of the extension.
182 * @param string $reason A string representation of why the extension is unavailable.
183 * @param array $details A free-form array containing more information on why the extension is unavailable.
184 */
185 public static function set_extension_unavailable( $slug, $reason, $details = array() ) {
186 if (
187 // Extensions that require a plan may be eligible for upgrades.
188 'missing_plan' === $reason
189 && (
190 /**
191 * Filter 'jetpack_block_editor_enable_upgrade_nudge' with `true` to enable or `false`
192 * to disable paid feature upgrade nudges in the block editor.
193 *
194 * When this is changed to default to `true`, you should also update `modules/memberships/class-jetpack-memberships.php`
195 * See https://github.com/Automattic/jetpack/pull/13394#pullrequestreview-293063378
196 *
197 * @since 7.7.0
198 *
199 * @param boolean
200 */
201 ! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false )
202 /** This filter is documented in _inc/lib/admin-pages/class.jetpack-react-page.php */
203 || ! apply_filters( 'jetpack_show_promotions', true )
204 )
205 ) {
206 // The block editor may apply an upgrade nudge if `missing_plan` is the reason.
207 // Add a descriptive suffix to disable behavior but provide informative reason.
208 $reason .= '__nudge_disabled';
209 }
210 $slug = self::remove_extension_prefix( $slug );
211 self::$availability[ $slug ] = array(
212 'reason' => $reason,
213 'details' => $details,
214 );
215 }
216
217 /**
218 * Used to initialize the class, no longer in use.
219 *
220 * @return void
221 * @deprecated 12.2 No longer needed.
222 */
223 public static function init() {
224 _deprecated_function( __METHOD__, '12.2' );
225 }
226
227 /**
228 * Resets the class to its original state
229 *
230 * Used in unit tests
231 *
232 * @return void
233 */
234 public static function reset() {
235 self::$extensions = null;
236 self::$availability = array();
237 self::$cached_availability = null;
238 }
239
240 /**
241 * Return the Gutenberg extensions (blocks and plugins) directory
242 *
243 * @return string The Gutenberg extensions directory
244 */
245 public static function get_blocks_directory() {
246 /**
247 * Filter to select Gutenberg blocks directory
248 *
249 * @since 6.9.0
250 *
251 * @param string default: '_inc/blocks/'
252 */
253 return apply_filters( 'jetpack_blocks_directory', '_inc/blocks/' );
254 }
255
256 /**
257 * Checks for a given .json file in the blocks folder.
258 *
259 * @deprecated 14.3
260 *
261 * @param string $preset The name of the .json file to look for.
262 *
263 * @return bool True if the file is found.
264 */
265 public static function preset_exists( $preset ) {
266 _deprecated_function( __METHOD__, '14.3' );
267 return file_exists( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $preset . '.json' );
268 }
269
270 /**
271 * Decodes JSON loaded from the preset file in the blocks folder
272 *
273 * @since 14.3 Deprecated argument. Only one value is ever used.
274 *
275 * @param null $deprecated No longer used.
276 *
277 * @return mixed Returns an object if the file is present, or false if a valid .json file is not present.
278 */
279 public static function get_preset( $deprecated = null ) {
280 if ( $deprecated ) {
281 _deprecated_argument( __METHOD__, '$$next-version', 'The $preset argument is no longer needed or used.' );
282 }
283
284 if ( self::$preset_cache ) {
285 return self::$preset_cache;
286 }
287
288 self::$preset_cache = json_decode(
289 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
290 file_get_contents( JETPACK__PLUGIN_DIR . self::get_blocks_directory() . 'index.json' )
291 );
292 return self::$preset_cache;
293 }
294
295 /**
296 * Returns a list of Jetpack Gutenberg extensions (blocks and plugins), based on index.json
297 *
298 * @return array A list of blocks: eg [ 'publicize', 'markdown' ]
299 */
300 public static function get_jetpack_gutenberg_extensions_allowed_list() {
301 $preset_extensions_manifest = ( defined( 'TESTING_IN_JETPACK' ) && TESTING_IN_JETPACK ) ? array() : self::get_preset();
302 $blocks_variation = self::blocks_variation();
303
304 return self::get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation );
305 }
306
307 /**
308 * Returns a diff from a combined list of allowed extensions and extensions determined to be excluded
309 *
310 * @param array $allowed_extensions An array of allowed extensions.
311 *
312 * @return array A list of blocks: eg array( 'publicize', 'markdown' )
313 */
314 public static function get_available_extensions( $allowed_extensions = null ) {
315 $exclusions = get_option( 'jetpack_excluded_extensions', array() );
316 $allowed_extensions = $allowed_extensions === null ? self::get_jetpack_gutenberg_extensions_allowed_list() : $allowed_extensions;
317
318 return array_diff( $allowed_extensions, $exclusions );
319 }
320
321 /**
322 * Return true if the extension has been registered and there's nothing in the availablilty array.
323 *
324 * @param string $extension The name of the extension.
325 *
326 * @return bool whether the extension has been registered and there's nothing in the availablilty array.
327 */
328 public static function is_registered_and_no_entry_in_availability( $extension ) {
329 return self::is_registered( 'jetpack/' . $extension ) && ! isset( self::$availability[ $extension ] );
330 }
331
332 /**
333 * Return true if the extension has a true entry in the availablilty array.
334 *
335 * @param string $extension The name of the extension.
336 *
337 * @return bool whether the extension has a true entry in the availablilty array.
338 */
339 public static function is_available( $extension ) {
340 return isset( self::$availability[ $extension ] ) && true === self::$availability[ $extension ];
341 }
342
343 /**
344 * Get the availability of each block / plugin, or return the cached availability
345 * if it has already been calculated. Avoids re-registering extensions when not
346 * necessary.
347 *
348 * @return array A list of block and plugins and their availability status.
349 */
350 public static function get_cached_availability() {
351 if ( null === self::$cached_availability ) {
352 self::$cached_availability = self::get_availability();
353 }
354 return self::$cached_availability;
355 }
356
357 /**
358 * Get availability of each block / plugin.
359 *
360 * @return array A list of block and plugins and their availablity status
361 */
362 public static function get_availability() {
363 /**
364 * Fires before Gutenberg extensions availability is computed.
365 *
366 * In the function call you supply, use `Blocks::jetpack_register_block()` to set a block as available.
367 * Alternatively, use `Jetpack_Gutenberg::set_extension_available()` (for a non-block plugin), and
368 * `Jetpack_Gutenberg::set_extension_unavailable()` (if the block or plugin should not be registered
369 * but marked as unavailable).
370 *
371 * @since 7.0.0
372 */
373 do_action( 'jetpack_register_gutenberg_extensions' );
374
375 $available_extensions = array();
376
377 foreach ( static::get_extensions() as $extension ) {
378 $is_available = self::is_registered_and_no_entry_in_availability( $extension ) || self::is_available( $extension );
379 $available_extensions[ $extension ] = array(
380 'available' => $is_available,
381 );
382
383 if ( ! $is_available ) {
384 $reason = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['reason'] : 'missing_module';
385 $details = isset( self::$availability[ $extension ] ) ? self::$availability[ $extension ]['details'] : array();
386 $available_extensions[ $extension ]['unavailable_reason'] = $reason;
387 $available_extensions[ $extension ]['details'] = $details;
388 }
389 }
390
391 return $available_extensions;
392 }
393
394 /**
395 * Return the list of extensions that are available.
396 *
397 * @since 11.9
398 *
399 * @return array A list of block and plugins and their availability status.
400 */
401 public static function get_extensions() {
402 if ( ! static::should_load() ) {
403 return array();
404 }
405
406 if ( null === self::$extensions ) {
407 /**
408 * Filter the list of block editor extensions that are available through Jetpack.
409 *
410 * @since 7.0.0
411 *
412 * @param array
413 */
414 self::$extensions = apply_filters( 'jetpack_set_available_extensions', self::get_available_extensions() );
415 }
416
417 return self::$extensions;
418 }
419
420 /**
421 * Check if an extension/block is already registered
422 *
423 * @since 7.2
424 *
425 * @param string $slug Name of extension/block to check.
426 *
427 * @return bool
428 */
429 public static function is_registered( $slug ) {
430 return WP_Block_Type_Registry::get_instance()->is_registered( $slug );
431 }
432
433 /**
434 * Check if Gutenberg editor is available
435 *
436 * @since 6.7.0
437 *
438 * @return bool
439 */
440 public static function is_gutenberg_available() {
441 return true;
442 }
443
444 /**
445 * Check whether conditions indicate Gutenberg Extensions (blocks and plugins) should be loaded
446 *
447 * Loading blocks and plugins is enabled by default and may be disabled via filter:
448 * add_filter( 'jetpack_gutenberg', '__return_false' );
449 *
450 * @since 6.9.0
451 *
452 * @return bool
453 */
454 public static function should_load() {
455 if ( ! Jetpack::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
456 return false;
457 }
458
459 $return = true;
460
461 if ( ! ( new Modules() )->is_active( 'blocks' ) ) {
462 $return = false;
463 }
464
465 /**
466 * Filter to enable Gutenberg blocks.
467 *
468 * Defaults to true if (connected or in offline mode) and the Blocks module is active.
469 *
470 * @since 6.5.0
471 * @since 13.9 Filter is able to activate or deactivate Gutenberg blocks.
472 *
473 * @param bool true Whether to load Gutenberg blocks
474 */
475 return (bool) apply_filters( 'jetpack_gutenberg', $return );
476 }
477
478 /**
479 * Queue a script to set `Jetpack_Block_Assets_Base_Url`.
480 *
481 * In certain cases Webpack needs to know a base to load additional assets from.
482 * Normally it can determine that itself, but when JS concatenation is involved that tends to confuse it.
483 * We work around that by explicitly outputting a variable with the correct URL.
484 * We set that as its own "script" so we can reliably only output it once.
485 */
486 private static function register_blocks_assets_base_url() {
487 if ( ! wp_script_is( 'jetpack-blocks-assets-base-url', 'registered' ) ) {
488 // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- No actual script, so no version needed.
489 wp_register_script( 'jetpack-blocks-assets-base-url', false, array(), null, array( 'in_footer' => false ) );
490 $json_encode_flags = JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP;
491 if ( get_option( 'blog_charset' ) === 'UTF-8' ) {
492 $json_encode_flags |= JSON_UNESCAPED_UNICODE;
493 }
494 wp_add_inline_script(
495 'jetpack-blocks-assets-base-url',
496 'var Jetpack_Block_Assets_Base_Url=' . wp_json_encode( plugins_url( self::get_blocks_directory(), JETPACK__PLUGIN_FILE ), $json_encode_flags ) . ';',
497 'before'
498 );
499 }
500 }
501
502 /**
503 * Only enqueue block assets when needed.
504 *
505 * @param string $type Slug of the block or absolute path to the block source code directory.
506 * @param array $script_dependencies Script dependencies. Will be merged with automatically
507 * detected script dependencies from the webpack build.
508 *
509 * @return void
510 */
511 public static function load_assets_as_required( $type, $script_dependencies = array() ) {
512 if ( is_admin() ) {
513 // A block's view assets will not be required in wp-admin.
514 return;
515 }
516
517 // Retrieve the feature from block.json if a path is passed.
518 if ( path_is_absolute( $type ) ) {
519 $metadata = Blocks::get_block_metadata_from_file( Blocks::get_path_to_block_metadata( $type ) );
520 $feature = Blocks::get_block_feature_from_metadata( $metadata );
521
522 if ( ! empty( $feature ) ) {
523 $type = $feature;
524 }
525 }
526
527 $type = sanitize_title_with_dashes( $type );
528 self::load_styles_as_required( $type );
529 self::load_scripts_as_required( $type, $script_dependencies );
530 }
531
532 /**
533 * Only enqueue block sytles when needed.
534 *
535 * @param string $type Slug of the block.
536 *
537 * @since 7.2.0
538 *
539 * @return void
540 */
541 public static function load_styles_as_required( $type ) {
542 if ( is_admin() ) {
543 // A block's view assets will not be required in wp-admin.
544 return;
545 }
546
547 // Enqueue styles.
548 $style_relative_path = self::get_blocks_directory() . $type . '/view' . ( is_rtl() ? '.rtl' : '' ) . '.css';
549 if ( self::block_has_asset( $style_relative_path ) ) {
550 $style_version = self::get_asset_version( $style_relative_path );
551 $view_style = plugins_url( $style_relative_path, JETPACK__PLUGIN_FILE );
552 $view_style = add_query_arg( 'minify', 'false', $view_style );
553
554 // If this is a customizer preview, render the style directly to the preview after autosave.
555 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
556 if ( is_customize_preview() && ! empty( $_GET['customize_autosaved'] ) ) {
557 // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
558 echo '<link rel="stylesheet" id="jetpack-block-' . esc_attr( $type ) . '" href="' . esc_attr( $view_style ) . '&amp;ver=' . esc_attr( $style_version ) . '" media="all">';
559 } else {
560 wp_enqueue_style( 'jetpack-block-' . $type, $view_style, array(), $style_version );
561 wp_style_add_data( 'jetpack-block-' . $type, 'path', JETPACK__PLUGIN_DIR . $style_relative_path );
562 }
563 }
564 }
565
566 /**
567 * Only enqueue block scripts when needed.
568 *
569 * @param string $type Slug of the block.
570 * @param array $script_dependencies Script dependencies. Will be merged with automatically
571 * detected script dependencies from the webpack build.
572 *
573 * @since 7.2.0
574 *
575 * @return void
576 */
577 public static function load_scripts_as_required( $type, $script_dependencies = array() ) {
578 if ( is_admin() ) {
579 // A block's view assets will not be required in wp-admin.
580 return;
581 }
582
583 self::register_blocks_assets_base_url();
584
585 // Enqueue script.
586 $script_relative_path = self::get_blocks_directory() . $type . '/view.js';
587 $script_deps_path = JETPACK__PLUGIN_DIR . self::get_blocks_directory() . $type . '/view.asset.php';
588 $script_dependencies[] = 'jetpack-blocks-assets-base-url';
589 if ( file_exists( $script_deps_path ) ) {
590 $asset_manifest = include $script_deps_path;
591 $script_dependencies = array_unique( array_merge( $script_dependencies, $asset_manifest['dependencies'] ) );
592 }
593
594 if ( ! Blocks::is_amp_request() && self::block_has_asset( $script_relative_path ) ) {
595 $script_version = self::get_asset_version( $script_relative_path );
596 $view_script = plugins_url( $script_relative_path, JETPACK__PLUGIN_FILE );
597 $view_script = add_query_arg( 'minify', 'false', $view_script );
598
599 // Enqueue dependencies.
600 wp_enqueue_script( 'jetpack-block-' . $type, $view_script, $script_dependencies, $script_version, false );
601
602 // If this is a customizer preview, enqueue the dependencies and render the script directly to the preview after autosave.
603 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
604 if ( is_customize_preview() && ! empty( $_GET['customize_autosaved'] ) ) {
605 // The Map block is dependent on wp-element, and it doesn't appear to to be possible to load
606 // this dynamically into the customizer iframe currently.
607 if ( 'map' === $type ) {
608 echo '<div>' . esc_html_e( 'No map preview available. Publish and refresh to see this widget.', 'jetpack' ) . '</div>';
609 echo '<script>';
610 echo 'Array.from(document.getElementsByClassName(\'wp-block-jetpack-map\')).forEach(function(element){element.style.display = \'none\';})';
611 echo '</script>';
612 } else {
613 echo '<script id="jetpack-block-' . esc_attr( $type ) . '" src="' . esc_attr( $view_script ) . '&amp;ver=' . esc_attr( $script_version ) . '"></script>';
614 }
615 }
616 }
617 }
618
619 /**
620 * Check if an asset exists for a block.
621 *
622 * @param string $file Path of the file we are looking for.
623 *
624 * @return bool $block_has_asset Does the file exist.
625 */
626 public static function block_has_asset( $file ) {
627 return file_exists( JETPACK__PLUGIN_DIR . $file );
628 }
629
630 /**
631 * Get the version number to use when loading the file. Allows us to bypass cache when developing.
632 *
633 * @param string $file Path of the file we are looking for.
634 *
635 * @return string $script_version Version number.
636 */
637 public static function get_asset_version( $file ) {
638 return Jetpack::is_development_version() && self::block_has_asset( $file )
639 ? filemtime( JETPACK__PLUGIN_DIR . $file )
640 : JETPACK__VERSION;
641 }
642
643 /**
644 * Load Gutenberg editor assets
645 *
646 * @since 6.7.0
647 *
648 * @return void
649 */
650 public static function enqueue_block_editor_assets() {
651 if ( ! self::should_load() ) {
652 return;
653 }
654
655 /**
656 * This can be called multiple times per page load in the admin, during the `enqueue_block_assets` action.
657 * These assets are necessary for the admin for editing but are not necessary for each pattern preview.
658 * Therefore we dequeue them, so they don't load for each pattern preview iframe.
659 */
660 if ( ! wp_should_load_block_editor_scripts_and_styles() ) {
661 wp_dequeue_script( 'jp-tracks' );
662 wp_dequeue_script( 'jetpack-blocks-editor' );
663
664 return;
665 }
666
667 $status = new Status();
668
669 // Required for Analytics. See _inc/lib/admin-pages/class.jetpack-admin-page.php.
670 if ( ! $status->is_offline_mode() && Jetpack::is_connection_ready() ) {
671 wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
672 }
673
674 $blocks_dir = self::get_blocks_directory();
675 $blocks_variation = self::blocks_variation();
676
677 if ( 'production' !== $blocks_variation ) {
678 $blocks_env = '-' . esc_attr( $blocks_variation );
679 } else {
680 $blocks_env = '';
681 }
682
683 self::register_blocks_assets_base_url();
684
685 Assets::register_script(
686 'jetpack-blocks-editor',
687 "{$blocks_dir}editor{$blocks_env}.js",
688 JETPACK__PLUGIN_FILE,
689 array(
690 'textdomain' => 'jetpack',
691 'dependencies' => array( 'jetpack-blocks-assets-base-url' ),
692 )
693 );
694
695 // Hack around #20357 (specifically, that the editor bundle depends on
696 // wp-edit-post but wp-edit-post's styles break the Widget Editor and
697 // Site Editor) until a real fix gets unblocked.
698 // @todo Remove this once #20357 is properly fixed.
699 $wp_styles_fix = wp_styles()->query( 'jetpack-blocks-editor', 'registered' );
700 if ( empty( $wp_styles_fix ) ) {
701 wp_die( 'Your installation of Jetpack is incomplete. Please run "jetpack build plugins/jetpack" in your dev env.' );
702 }
703 wp_styles()->query( 'jetpack-blocks-editor', 'registered' )->deps = array();
704
705 Assets::enqueue_script( 'jetpack-blocks-editor' );
706
707 if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
708 $user = wp_get_current_user();
709 $user_data = array(
710 'email' => $user->user_email,
711 'userid' => $user->ID,
712 'username' => $user->user_login,
713 );
714 $blog_id = get_current_blog_id();
715 $is_current_user_connected = true;
716 } else {
717 $user_data = Jetpack_Tracks_Client::get_connected_user_tracks_identity();
718 $blog_id = Jetpack_Options::get_option( 'id', 0 );
719 $is_current_user_connected = ( new Connection_Manager( 'jetpack' ) )->is_user_connected();
720 }
721
722 if ( $blocks_variation === 'beta' && $is_current_user_connected ) {
723 wp_enqueue_style( 'recoleta-font', '//s1.wp.com/i/fonts/recoleta/css/400.min.css', array(), Constants::get_constant( 'JETPACK__VERSION' ) );
724 }
725 // AI Assistant
726 $ai_assistant_state = array(
727 'is-enabled' => apply_filters( 'jetpack_ai_enabled', true ),
728 );
729
730 $screen_base = null;
731 if ( function_exists( 'get_current_screen' ) ) {
732 $screen_base = get_current_screen()->base;
733 }
734
735 $modules = array();
736 if ( class_exists( 'Jetpack_Core_API_Module_List_Endpoint' ) ) {
737 $module_list_endpoint = new Jetpack_Core_API_Module_List_Endpoint();
738 $modules = $module_list_endpoint->get_modules();
739 }
740
741 $jetpack_plan = Jetpack_Plan::get();
742 $initial_state = array(
743 'available_blocks' => self::get_availability(),
744 'blocks_variation' => $blocks_variation,
745 'modules' => $modules,
746 'jetpack' => array(
747 'is_active' => Jetpack::is_connection_ready(),
748 'is_current_user_connected' => $is_current_user_connected,
749 /** This filter is documented in class.jetpack-gutenberg.php */
750 'enable_upgrade_nudge' => apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false ),
751 'is_private_site' => $status->is_private_site(),
752 'is_coming_soon' => $status->is_coming_soon(),
753 'is_offline_mode' => $status->is_offline_mode(),
754 'is_newsletter_feature_enabled' => class_exists( '\Jetpack_Memberships' ),
755 // this is the equivalent of JP initial state siteData.showMyJetpack (class-jetpack-redux-state-helper)
756 // used to determine if we can link to My Jetpack from the block editor
757 'is_my_jetpack_available' => My_Jetpack_Initializer::should_initialize(),
758 'jetpack_plan' => array(
759 'data' => $jetpack_plan['product_slug'],
760 ),
761 /**
762 * Enable the RePublicize UI in the block editor context.
763 *
764 * @module publicize
765 *
766 * @since 10.3.0
767 * @deprecated 11.5 This is a feature flag that is no longer used.
768 *
769 * @param bool true Enable the RePublicize UI in the block editor context. Defaults to true.
770 */
771 'republicize_enabled' => apply_filters( 'jetpack_block_editor_republicize_feature', true ),
772 ),
773 'siteFragment' => $status->get_site_suffix(),
774 'adminUrl' => esc_url( admin_url() ),
775 'tracksUserData' => $user_data,
776 'wpcomBlogId' => $blog_id,
777 'allowedMimeTypes' => wp_get_mime_types(),
778 'siteLocale' => str_replace( '_', '-', get_locale() ),
779 'ai-assistant' => $ai_assistant_state,
780 'screenBase' => $screen_base,
781 'pluginBasePath' => plugins_url( '', Constants::get_constant( 'JETPACK__PLUGIN_FILE' ) ),
782 );
783
784 if ( Jetpack::is_module_active( 'publicize' ) && function_exists( 'publicize_init' ) ) {
785 $publicize = publicize_init();
786 $jetpack_social_settings = new Automattic\Jetpack\Publicize\Jetpack_Social_Settings\Settings();
787 $social_initial_state = $jetpack_social_settings->get_initial_state();
788
789 $initial_state['social'] = array(
790 'sharesData' => $publicize->get_publicize_shares_info( $blog_id ),
791 'hasPaidPlan' => $publicize->has_paid_plan(),
792 'hasPaidFeatures' => $publicize->has_paid_features(),
793 'isEnhancedPublishingEnabled' => $publicize->has_enhanced_publishing_feature(),
794 'isSocialImageGeneratorAvailable' => $social_initial_state['socialImageGeneratorSettings']['available'],
795 'isSocialImageGeneratorEnabled' => $social_initial_state['socialImageGeneratorSettings']['enabled'],
796 'dismissedNotices' => Dismissed_Notices::get_dismissed_notices(),
797 'supportedAdditionalConnections' => $publicize->get_supported_additional_connections(),
798 'jetpackSharingSettingsUrl' => esc_url_raw( admin_url( 'admin.php?page=jetpack#/sharing' ) ),
799 'userConnectionUrl' => esc_url_raw( admin_url( 'admin.php?page=my-jetpack#/connection' ) ),
800 'useAdminUiV1' => $social_initial_state['useAdminUiV1'],
801 );
802
803 // Add connectionData if we are using the new Connection UI.
804 if ( $social_initial_state['useAdminUiV1'] ) {
805 $initial_state['social']['connectionData'] = $social_initial_state['connectionData'];
806
807 $initial_state['social']['connectionRefreshPath'] = $social_initial_state['connectionRefreshPath'];
808 }
809
810 $initial_state['social']['featureFlags'] = $social_initial_state['featureFlags'];
811 }
812
813 wp_localize_script(
814 'jetpack-blocks-editor',
815 'Jetpack_Editor_Initial_State',
816 $initial_state
817 );
818
819 // Adds Connection package initial state.
820 Connection_Initial_State::render_script( 'jetpack-blocks-editor' );
821 }
822
823 /**
824 * Some blocks do not depend on a specific module,
825 * and can consequently be loaded outside of the usual modules.
826 * We will look for such modules in the extensions/ directory.
827 *
828 * @since 7.1.0
829 * @see wp_common_block_scripts_and_styles()
830 */
831 public static function load_independent_blocks() {
832 if ( self::should_load() ) {
833 /**
834 * Look for files that match our list of available Jetpack Gutenberg extensions (blocks and plugins).
835 * If available, load them.
836 */
837 $directories = array( 'blocks', 'plugins', 'extended-blocks' );
838
839 foreach ( static::get_extensions() as $extension ) {
840 foreach ( $directories as $dirname ) {
841 $path = JETPACK__PLUGIN_DIR . "extensions/{$dirname}/{$extension}/{$extension}.php";
842
843 if ( file_exists( $path ) ) {
844 include_once $path;
845 continue 2;
846 }
847 }
848 }
849 }
850 }
851
852 /**
853 * Loads PHP components of block editor extensions.
854 *
855 * @since 8.9.0
856 */
857 public static function load_block_editor_extensions() {
858 if ( self::should_load() ) {
859 // Block editor extensions to load.
860 $extensions_to_load = array(
861 'extended-blocks',
862 'plugins',
863 );
864
865 // Collect the extension paths.
866 foreach ( $extensions_to_load as $extension_to_load ) {
867 $extensions_folder = glob( JETPACK__PLUGIN_DIR . 'extensions/' . $extension_to_load . '/*' );
868
869 // Require each of the extension files, in case it exists.
870 foreach ( $extensions_folder as $extension_folder ) {
871 $name = basename( $extension_folder );
872 $extension_file_path = JETPACK__PLUGIN_DIR . 'extensions/' . $extension_to_load . '/' . $name . '/' . $name . '.php';
873
874 if ( file_exists( $extension_file_path ) ) {
875 include_once $extension_file_path;
876 }
877 }
878 }
879 }
880 }
881
882 /**
883 * Determine whether a site should use the default set of blocks, or a custom set.
884 * Possible variations are currently beta, experimental, and production.
885 *
886 * @since 8.1.0
887 *
888 * @return string $block_varation production|beta|experimental
889 */
890 public static function blocks_variation() {
891 // Default to production blocks.
892 $block_varation = 'production';
893
894 /*
895 * Prefer to use this JETPACK_BLOCKS_VARIATION constant
896 * or the jetpack_blocks_variation filter
897 * to set the block variation in your code.
898 */
899 $default = Constants::get_constant( 'JETPACK_BLOCKS_VARIATION' );
900 if ( ! empty( $default ) && in_array( $default, array( 'beta', 'experimental', 'production' ), true ) ) {
901 $block_varation = $default;
902 }
903
904 /**
905 * Alternative to `JETPACK_BETA_BLOCKS`, set to `true` to load Beta Blocks.
906 *
907 * @since 6.9.0
908 * @deprecated 11.8.0 Use jetpack_blocks_variation filter instead.
909 *
910 * @param boolean
911 */
912 $is_beta = apply_filters_deprecated(
913 'jetpack_load_beta_blocks',
914 array( false ),
915 'jetpack-11.8.0',
916 'jetpack_blocks_variation'
917 );
918
919 /*
920 * Switch to beta blocks if you use the JETPACK_BETA_BLOCKS constant
921 * or the deprecated jetpack_load_beta_blocks filter.
922 * This only applies when not using the newer JETPACK_BLOCKS_VARIATION constant.
923 */
924 if (
925 empty( $default )
926 && (
927 $is_beta
928 || Constants::is_true( 'JETPACK_BETA_BLOCKS' )
929 )
930 ) {
931 $block_varation = 'beta';
932 }
933
934 /**
935 * Alternative to `JETPACK_EXPERIMENTAL_BLOCKS`, set to `true` to load Experimental Blocks.
936 *
937 * @since 6.9.0
938 * @deprecated 11.8.0 Use jetpack_blocks_variation filter instead.
939 *
940 * @param boolean
941 */
942 $is_experimental = apply_filters_deprecated(
943 'jetpack_load_experimental_blocks',
944 array( false ),
945 'jetpack-11.8.0',
946 'jetpack_blocks_variation'
947 );
948
949 /*
950 * Switch to experimental blocks if you use the JETPACK_EXPERIMENTAL_BLOCKS constant
951 * or the deprecated jetpack_load_experimental_blocks filter.
952 * This only applies when not using the newer JETPACK_BLOCKS_VARIATION constant.
953 */
954 if (
955 empty( $default )
956 && (
957 $is_experimental
958 || Constants::is_true( 'JETPACK_EXPERIMENTAL_BLOCKS' )
959 )
960 ) {
961 $block_varation = 'experimental';
962 }
963
964 /**
965 * Allow customizing the variation of blocks in use on a site.
966 * Overwrites any previously set values, whether by constant or filter.
967 *
968 * @since 8.1.0
969 *
970 * @param string $block_variation Can be beta, experimental, and production. Defaults to production.
971 */
972 return apply_filters( 'jetpack_blocks_variation', $block_varation );
973 }
974
975 /**
976 * Get a list of extensions available for the variation you chose.
977 *
978 * @since 8.1.0
979 *
980 * @param object $preset_extensions_manifest List of extensions available in Jetpack.
981 * @param string $blocks_variation Subset of blocks. production|beta|experimental.
982 *
983 * @return array $preset_extensions Array of extensions for that variation
984 */
985 public static function get_extensions_preset_for_variation( $preset_extensions_manifest, $blocks_variation ) {
986 $preset_extensions = isset( $preset_extensions_manifest->{ $blocks_variation } )
987 ? (array) $preset_extensions_manifest->{ $blocks_variation }
988 : array();
989
990 /*
991 * Experimental and Beta blocks need the production blocks as well.
992 */
993 if (
994 'experimental' === $blocks_variation
995 || 'beta' === $blocks_variation
996 ) {
997 $production_extensions = isset( $preset_extensions_manifest->production )
998 ? (array) $preset_extensions_manifest->production
999 : array();
1000
1001 $preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
1002 }
1003
1004 /*
1005 * Beta blocks need the experimental blocks as well.
1006 *
1007 * If you've chosen to see Beta blocks,
1008 * we want to make all blocks available to you:
1009 * - Production
1010 * - Experimental
1011 * - Beta
1012 */
1013 if ( 'beta' === $blocks_variation ) {
1014 $production_extensions = isset( $preset_extensions_manifest->experimental )
1015 ? (array) $preset_extensions_manifest->experimental
1016 : array();
1017
1018 $preset_extensions = array_unique( array_merge( $preset_extensions, $production_extensions ) );
1019 }
1020
1021 return $preset_extensions;
1022 }
1023
1024 /**
1025 * Validate a URL used in a SSR block.
1026 *
1027 * @since 8.3.0
1028 *
1029 * @param string $url URL saved as an attribute in block.
1030 * @param array $allowed Array of allowed hosts for that block, or regexes to check against.
1031 * @param bool $is_regex Array of regexes matching the URL that could be used in block.
1032 *
1033 * @return bool|string
1034 */
1035 public static function validate_block_embed_url( $url, $allowed = array(), $is_regex = false ) {
1036 if (
1037 empty( $url )
1038 || ! is_array( $allowed )
1039 || empty( $allowed )
1040 ) {
1041 return false;
1042 }
1043
1044 $url_components = wp_parse_url( $url );
1045
1046 // Bail early if we cannot find a host.
1047 if ( empty( $url_components['host'] ) ) {
1048 return false;
1049 }
1050
1051 // Normalize URL.
1052 $url = sprintf(
1053 '%s://%s%s%s',
1054 isset( $url_components['scheme'] ) ? $url_components['scheme'] : 'https',
1055 $url_components['host'],
1056 isset( $url_components['path'] ) ? $url_components['path'] : '/',
1057 isset( $url_components['query'] ) ? '?' . $url_components['query'] : ''
1058 );
1059
1060 if ( ! empty( $url_components['fragment'] ) ) {
1061 $url = $url . '#' . rawurlencode( $url_components['fragment'] );
1062 }
1063
1064 /*
1065 * If we're using an allowed list of hosts,
1066 * check if the URL belongs to one of the domains allowed for that block.
1067 */
1068 if (
1069 false === $is_regex
1070 && in_array( $url_components['host'], $allowed, true )
1071 ) {
1072 return $url;
1073 }
1074
1075 /*
1076 * If we are using an array of regexes to check against,
1077 * loop through that.
1078 */
1079 if ( true === $is_regex ) {
1080 foreach ( $allowed as $regex ) {
1081 if ( 1 === preg_match( $regex, $url ) ) {
1082 return $url;
1083 }
1084 }
1085 }
1086
1087 return false;
1088 }
1089
1090 /**
1091 * Determines whether a preview of the block with an upgrade nudge should
1092 * be displayed for admins on the site frontend.
1093 *
1094 * @since 8.4.0
1095 *
1096 * @param array $availability_for_block The availability for the block.
1097 *
1098 * @return bool
1099 */
1100 public static function should_show_frontend_preview( $availability_for_block ) {
1101 return (
1102 isset( $availability_for_block['details']['required_plan'] )
1103 && current_user_can( 'manage_options' )
1104 && ! is_feed()
1105 );
1106 }
1107
1108 /**
1109 * Output an UpgradeNudge Component on the frontend of a site.
1110 *
1111 * @since 8.4.0
1112 *
1113 * @param string $plan The plan that users need to purchase to make the block work.
1114 *
1115 * @return string
1116 */
1117 public static function upgrade_nudge( $plan ) {
1118 require_once JETPACK__PLUGIN_DIR . '_inc/lib/components.php';
1119 return Jetpack_Components::render_upgrade_nudge(
1120 array(
1121 'plan' => $plan,
1122 )
1123 );
1124 }
1125
1126 /**
1127 * Output a notice within a block.
1128 *
1129 * @since 8.6.0
1130 *
1131 * @param string $message Notice we want to output.
1132 * @param string $status Status of the notice. Can be one of success, info, warning, error. info by default.
1133 * @param string $classes List of CSS classes.
1134 *
1135 * @return string
1136 */
1137 public static function notice( $message, $status = 'info', $classes = '' ) {
1138 if (
1139 empty( $message )
1140 || ! in_array( $status, array( 'success', 'info', 'warning', 'error' ), true )
1141 ) {
1142 return '';
1143 }
1144
1145 $color = '';
1146 switch ( $status ) {
1147 case 'success':
1148 $color = '#00a32a';
1149 break;
1150 case 'warning':
1151 $color = '#dba617';
1152 break;
1153 case 'error':
1154 $color = '#d63638';
1155 break;
1156 case 'info':
1157 default:
1158 $color = '#72aee6';
1159 break;
1160 }
1161
1162 return sprintf(
1163 '<div class="jetpack-block__notice %1$s %3$s" style="border-left:5px solid %4$s;padding:1em;background-color:#f8f9f9;">%2$s</div>',
1164 esc_attr( $status ),
1165 wp_kses(
1166 $message,
1167 array(
1168 'br' => array(),
1169 'p' => array(),
1170 'a' => array(
1171 'href' => array(),
1172 'target' => array(),
1173 'rel' => array(),
1174 ),
1175 )
1176 ),
1177 esc_attr( $classes ),
1178 sanitize_hex_color( $color )
1179 );
1180 }
1181
1182 /**
1183 * Retrieve site-specific features for Simple sites.
1184 *
1185 * We're caching the data for the lifetime of the request, because it can be slow to calculate,
1186 * and it can be called multiple times per single request.
1187 *
1188 * We intentionally don't use object caching or any other type of persistent caching,
1189 * in order to avoid complex cache invalidation on subscription addition or removal.
1190 *
1191 * @since 10.7
1192 *
1193 * @return array
1194 */
1195 private static function get_site_specific_features() {
1196 $current_blog_id = get_current_blog_id();
1197
1198 if ( isset( self::$site_specific_features[ $current_blog_id ] ) ) {
1199 return self::$site_specific_features[ $current_blog_id ];
1200 }
1201
1202 if ( ! class_exists( 'Store_Product_List' ) ) {
1203 require WP_CONTENT_DIR . '/admin-plugins/wpcom-billing/store-product-list.php';
1204 }
1205
1206 $site_specific_features = Store_Product_List::get_site_specific_features_data( $current_blog_id );
1207 self::$site_specific_features[ $current_blog_id ] = $site_specific_features;
1208
1209 return $site_specific_features;
1210 }
1211
1212 /**
1213 * Set the availability of the block as the editor
1214 * is loaded.
1215 *
1216 * @param string $slug Slug of the block.
1217 */
1218 public static function set_availability_for_plan( $slug ) {
1219 $slug = self::remove_extension_prefix( $slug );
1220
1221 if ( Jetpack_Plan::supports( $slug ) ) {
1222 self::set_extension_available( $slug );
1223 return;
1224 }
1225
1226 // Check what's the minimum plan where the feature is available.
1227 $plan = '';
1228 $features_data = array();
1229 $is_simple_site = defined( 'IS_WPCOM' ) && IS_WPCOM;
1230 $is_atomic_site = ( new Host() )->is_woa_site();
1231
1232 if ( $is_simple_site || $is_atomic_site ) {
1233 // Simple sites.
1234 if ( $is_simple_site ) {
1235 $features_data = self::get_site_specific_features();
1236 } else {
1237 // Atomic sites.
1238 $option = get_option( 'jetpack_active_plan' );
1239 if ( isset( $option['features'] ) ) {
1240 $features_data = $option['features'];
1241 }
1242 }
1243
1244 if ( ! empty( $features_data['available'][ $slug ] ) ) {
1245 $plan = $features_data['available'][ $slug ][0];
1246 }
1247 } else {
1248 // Jetpack sites.
1249 $plan = Jetpack_Plan::get_minimum_plan_for_feature( $slug );
1250 }
1251
1252 self::set_extension_unavailable(
1253 $slug,
1254 'missing_plan',
1255 array(
1256 'required_feature' => $slug,
1257 'required_plan' => $plan,
1258 )
1259 );
1260 }
1261
1262 /**
1263 * Wraps the suplied render_callback in a function to check
1264 * the availability of the block before rendering it.
1265 *
1266 * @param string $slug The block slug, used to check for availability.
1267 * @param callable $render_callback The render_callback that will be called if the block is available.
1268 */
1269 public static function get_render_callback_with_availability_check( $slug, $render_callback ) {
1270 return function ( $prepared_attributes, $block_content, $block ) use ( $render_callback, $slug ) {
1271 $availability = self::get_cached_availability();
1272 $bare_slug = self::remove_extension_prefix( $slug );
1273 if ( isset( $availability[ $bare_slug ] ) && $availability[ $bare_slug ]['available'] ) {
1274 return call_user_func( $render_callback, $prepared_attributes, $block_content );
1275 }
1276
1277 // A preview of the block is rendered for admins on the frontend with an upgrade nudge.
1278 if ( isset( $availability[ $bare_slug ] ) ) {
1279 if ( self::should_show_frontend_preview( $availability[ $bare_slug ] ) ) {
1280 $block_preview = call_user_func( $render_callback, $prepared_attributes, $block_content );
1281
1282 // If the upgrade nudge isn't already being displayed by a parent block, display the nudge.
1283 if ( isset( $block->attributes['shouldDisplayFrontendBanner'] ) && $block->attributes['shouldDisplayFrontendBanner'] ) {
1284 $upgrade_nudge = self::upgrade_nudge( $availability[ $bare_slug ]['details']['required_plan'] );
1285 return $upgrade_nudge . $block_preview;
1286 }
1287
1288 return $block_preview;
1289 }
1290 }
1291
1292 return null;
1293 };
1294 }
1295
1296 /**
1297 * Display a message to site editors and roles above when a block is no longer supported.
1298 * This is only displayed on the frontend.
1299 *
1300 * @since 12.3
1301 *
1302 * @param string $block_content The block content.
1303 * @param array $block The full block, including name and attributes.
1304 *
1305 * @return string
1306 */
1307 public static function display_deprecated_block_message( $block_content, $block ) {
1308 if ( in_array( $block['blockName'], self::$deprecated_blocks, true ) ) {
1309 if ( current_user_can( 'edit_posts' ) ) {
1310 $block_content = self::notice(
1311 __( 'This block is no longer supported. Its contents will no longer be displayed to your visitors and as such this block should be removed.', 'jetpack' ),
1312 'warning',
1313 'jetpack-block-deprecated'
1314 );
1315 } else {
1316 $block_content = '';
1317 }
1318 }
1319
1320 return $block_content;
1321 }
1322
1323 /**
1324 * Temporarily bypasses _doing_it_wrong() notices for block metadata collection registration.
1325 *
1326 * WordPress 6.7 introduced block metadata collections (with strict path validation).
1327 * Any sites using symlinks for plugins will fail the validation which causes the metadata
1328 * collection to not be registered. However, the blocks will still fall back to the regular
1329 * registration and no functionality is affected.
1330 * While this validation is being discussed in WordPress Core (#62140),
1331 * this method allows registration to proceed by temporarily disabling
1332 * the relevant notice.
1333 *
1334 * @since 14.2
1335 *
1336 * @param bool $trigger Whether to trigger the error.
1337 * @param string $function The function that was called.
1338 * @param string $message A message explaining what was done incorrectly.
1339 * @param string $version The version of WordPress where the message was added.
1340 * @return bool Whether to trigger the error.
1341 */
1342 public static function bypass_block_metadata_doing_it_wrong( $trigger, $function, $message, $version ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
1343 if ( $function === 'WP_Block_Metadata_Registry::register_collection' ) {
1344 return false;
1345 }
1346 return $trigger;
1347 }
1348
1349 /**
1350 * Register block metadata collection for Jetpack blocks.
1351 * This allows for more efficient block metadata loading by avoiding
1352 * individual block.json file reads at runtime.
1353 *
1354 * Uses wp_register_block_metadata_collection() if available (WordPress 6.7+)
1355 * and if the manifest file exists. The manifest file is auto-generated
1356 * during the build process.
1357 *
1358 * Runs on plugins_loaded to ensure registration happens before individual
1359 * blocks register themselves on init.
1360 *
1361 * @static
1362 * @since 14.1
1363 * @return void
1364 */
1365 public static function register_block_metadata_collection() {
1366 $meta_file_path = JETPACK__PLUGIN_DIR . '_inc/blocks/blocks-manifest.php';
1367 if ( function_exists( 'wp_register_block_metadata_collection' ) && file_exists( $meta_file_path ) ) {
1368 add_filter( 'doing_it_wrong_trigger_error', array( __CLASS__, 'bypass_block_metadata_doing_it_wrong' ), 10, 4 );
1369
1370 // @phan-suppress-next-line PhanUndeclaredFunction -- New in WP 6.7. We're checking if it exists first. @phan-suppress-current-line UnusedPluginSuppression
1371 wp_register_block_metadata_collection(
1372 JETPACK__PLUGIN_DIR . '_inc/blocks/',
1373 $meta_file_path
1374 );
1375
1376 remove_filter( 'doing_it_wrong_trigger_error', array( __CLASS__, 'bypass_block_metadata_doing_it_wrong' ), 10 );
1377 }
1378 }
1379 }
1380
1381 if ( ( new Host() )->is_woa_site() ) {
1382 /**
1383 * Enable upgrade nudge for Atomic sites.
1384 * This feature is false as default,
1385 * so let's enable it through this filter.
1386 *
1387 * More doc: https://github.com/Automattic/jetpack/blob/trunk/projects/plugins/jetpack/extensions/README.md#upgrades-for-blocks
1388 */
1389 add_filter( 'jetpack_block_editor_enable_upgrade_nudge', '__return_true' );
1390 }
1391