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