PluginProbe
Gutenberg / 10.2.1
Gutenberg v10.2.1
23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 7.4.0 All 402 releases
gutenberg / lib / class-wp-theme-json-resolver.php

class-wp-theme-json-resolver.php in Gutenberg 10.2.1, at lib/class-wp-theme-json-resolver.php

524 lines 16.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Process the different data sources for site-level
4 * config and offers and API to work with them.
5 *
6 * @package gutenberg
7 */
8
9 /**
10 * Class that abstracts the processing
11 * of the different data sources.
12 */
13 class WP_Theme_JSON_Resolver {
14
15 /**
16 * Container for data coming from core.
17 *
18 * @var WP_Theme_JSON
19 */
20 private static $core = null;
21
22 /**
23 * Container for data coming from the theme.
24 *
25 * @var WP_Theme_JSON
26 */
27 private static $theme = null;
28
29 /**
30 * Whether or not the theme supports theme.json.
31 *
32 * @var boolean
33 */
34 private static $theme_has_support = null;
35
36 /**
37 * Container for data coming from the user.
38 *
39 * @var WP_Theme_JSON
40 */
41 private static $user = null;
42
43 /**
44 * Stores the ID of the custom post type
45 * that holds the user data.
46 *
47 * @var integer
48 */
49 private static $user_custom_post_type_id = null;
50
51 /**
52 * Processes a file that adheres to the theme.json
53 * schema and returns an array with its contents,
54 * or a void array if none found.
55 *
56 * @param string $file_path Path to file. Empty if no file.
57 *
58 * @return array Contents that adhere to the theme.json schema.
59 */
60 private static function read_json_file( $file_path ) {
61 $config = array();
62 if ( $file_path ) {
63 $decoded_file = json_decode(
64 file_get_contents( $file_path ),
65 true
66 );
67
68 $json_decoding_error = json_last_error();
69 if ( JSON_ERROR_NONE !== $json_decoding_error ) {
70 error_log( 'Error when decoding file schema: ' . json_last_error_msg() );
71 return $config;
72 }
73
74 if ( is_array( $decoded_file ) ) {
75 $config = $decoded_file;
76 }
77 }
78 return $config;
79 }
80
81 /**
82 * Converts a tree as in i18n-theme.json into a linear array
83 * containing metadata to translate a theme.json file.
84 *
85 * For example, given this input:
86 *
87 * {
88 * "settings": {
89 * "*": {
90 * "typography": {
91 * "fontSizes": [ { "name": "Font size name" } ],
92 * "fontStyles": [ { "name": "Font size name" } ]
93 * }
94 * }
95 * }
96 * }
97 *
98 * will return this output:
99 *
100 * [
101 * 0 => [
102 * 'path' => [ 'settings', '*', 'typography', 'fontSizes' ],
103 * 'key' => 'name',
104 * 'context' => 'Font size name'
105 * ],
106 * 1 => [
107 * 'path' => [ 'settings', '*', 'typography', 'fontStyles' ],
108 * 'key' => 'name',
109 * 'context' => 'Font style name'
110 * ]
111 * ]
112 *
113 * @param array $i18n_partial A tree that follows the format of i18n-theme.json.
114 * @param array $current_path Keeps track of the path as we walk down the given tree.
115 *
116 * @return array A linear array containing the paths to translate.
117 */
118 private static function extract_paths_to_translate( $i18n_partial, $current_path = array() ) {
119 $result = array();
120 foreach ( $i18n_partial as $property => $partial_child ) {
121 if ( is_numeric( $property ) ) {
122 foreach ( $partial_child as $key => $context ) {
123 return array(
124 array(
125 'path' => $current_path,
126 'key' => $key,
127 'context' => $context,
128 ),
129 );
130 }
131 }
132 $result = array_merge(
133 $result,
134 self::extract_paths_to_translate( $partial_child, array_merge( $current_path, array( $property ) ) )
135 );
136 }
137 return $result;
138 }
139
140 /**
141 * Returns a data structure used in theme.json translation.
142 *
143 * @return array An array of theme.json paths that are translatable and the keys that are translatable
144 */
145 public static function get_presets_to_translate() {
146 static $theme_json_i18n = null;
147 if ( null === $theme_json_i18n ) {
148 $file_structure = self::read_json_file( __DIR__ . '/experimental-i18n-theme.json' );
149 $theme_json_i18n = self::extract_paths_to_translate( $file_structure );
150 }
151 return $theme_json_i18n;
152 }
153
154 /**
155 * Given a theme.json structure modifies it in place
156 * to update certain values by its translated strings
157 * according to the language set by the user.
158 *
159 * @param array $theme_json The theme.json to translate.
160 * @param string $domain Optional. Text domain. Unique identifier for retrieving translated strings.
161 * Default 'default'.
162 *
163 * @return array Returns the modified $theme_json_structure.
164 */
165 private static function translate( $theme_json, $domain = 'default' ) {
166 if ( ! isset( $theme_json['settings'] ) ) {
167 return $theme_json;
168 }
169
170 $presets = self::get_presets_to_translate();
171 foreach ( $theme_json['settings'] as $setting_key => $settings ) {
172 if ( empty( $settings ) ) {
173 continue;
174 }
175
176 foreach ( $presets as $preset ) {
177 $path = array_slice( $preset['path'], 2 );
178 $key = $preset['key'];
179 $context = $preset['context'];
180
181 $array_to_translate = _wp_array_get( $theme_json['settings'][ $setting_key ], $path, null );
182 if ( null === $array_to_translate ) {
183 continue;
184 }
185
186 foreach ( $array_to_translate as $item_key => $item_to_translate ) {
187 if ( empty( $item_to_translate[ $key ] ) ) {
188 continue;
189 }
190
191 // phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText,WordPress.WP.I18n.NonSingularStringLiteralContext,WordPress.WP.I18n.NonSingularStringLiteralDomain
192 $array_to_translate[ $item_key ][ $key ] = translate_with_gettext_context( $array_to_translate[ $item_key ][ $key ], $context, $domain );
193 // phpcs:enable
194 }
195
196 gutenberg_experimental_set( $theme_json['settings'][ $setting_key ], $path, $array_to_translate );
197 }
198 }
199
200 return $theme_json;
201 }
202
203 /**
204 * Return core's origin config.
205 *
206 * @return WP_Theme_JSON Entity that holds core data.
207 */
208 public static function get_core_data() {
209 if ( null !== self::$core ) {
210 return self::$core;
211 }
212
213 $all_blocks = WP_Theme_JSON::ALL_BLOCKS_NAME;
214 $config = self::read_json_file( __DIR__ . '/experimental-default-theme.json' );
215 $config = self::translate( $config );
216
217 // Start i18n logic to remove when JSON i18 strings are extracted.
218 $default_colors_i18n = array(
219 'black' => __( 'Black', 'gutenberg' ),
220 'cyan-bluish-gray' => __( 'Cyan bluish gray', 'gutenberg' ),
221 'white' => __( 'White', 'gutenberg' ),
222 'pale-pink' => __( 'Pale pink', 'gutenberg' ),
223 'vivid-red' => __( 'Vivid red', 'gutenberg' ),
224 'luminous-vivid-orange' => __( 'Luminous vivid orange', 'gutenberg' ),
225 'luminous-vivid-amber' => __( 'Luminous vivid amber', 'gutenberg' ),
226 'light-green-cyan' => __( 'Light green cyan', 'gutenberg' ),
227 'vivid-green-cyan' => __( 'Vivid green cyan', 'gutenberg' ),
228 'pale-cyan-blue' => __( 'Pale cyan blue', 'gutenberg' ),
229 'vivid-cyan-blue' => __( 'Vivid cyan blue', 'gutenberg' ),
230 'vivid-purple' => __( 'Vivid purple', 'gutenberg' ),
231 );
232 if ( ! empty( $config['settings'][ $all_blocks ]['color']['palette'] ) ) {
233 foreach ( $config['settings'][ $all_blocks ]['color']['palette'] as $color_key => $color ) {
234 $config['settings'][ $all_blocks ]['color']['palette'][ $color_key ]['name'] = $default_colors_i18n[ $color['slug'] ];
235 }
236 }
237
238 $default_gradients_i18n = array(
239 'vivid-cyan-blue-to-vivid-purple' => __( 'Vivid cyan blue to vivid purple', 'gutenberg' ),
240 'light-green-cyan-to-vivid-green-cyan' => __( 'Light green cyan to vivid green cyan', 'gutenberg' ),
241 'luminous-vivid-amber-to-luminous-vivid-orange' => __( 'Luminous vivid amber to luminous vivid orange', 'gutenberg' ),
242 'luminous-vivid-orange-to-vivid-red' => __( 'Luminous vivid orange to vivid red', 'gutenberg' ),
243 'very-light-gray-to-cyan-bluish-gray' => __( 'Very light gray to cyan bluish gray', 'gutenberg' ),
244 'cool-to-warm-spectrum' => __( 'Cool to warm spectrum', 'gutenberg' ),
245 'blush-light-purple' => __( 'Blush light purple', 'gutenberg' ),
246 'blush-bordeaux' => __( 'Blush bordeaux', 'gutenberg' ),
247 'luminous-dusk' => __( 'Luminous dusk', 'gutenberg' ),
248 'pale-ocean' => __( 'Pale ocean', 'gutenberg' ),
249 'electric-grass' => __( 'Electric grass', 'gutenberg' ),
250 'midnight' => __( 'Midnight', 'gutenberg' ),
251 );
252 if ( ! empty( $config['settings'][ $all_blocks ]['color']['gradients'] ) ) {
253 foreach ( $config['settings'][ $all_blocks ]['color']['gradients'] as $gradient_key => $gradient ) {
254 $config['settings'][ $all_blocks ]['color']['gradients'][ $gradient_key ]['name'] = $default_gradients_i18n[ $gradient['slug'] ];
255 }
256 }
257
258 $default_font_sizes_i18n = array(
259 'small' => __( 'Small', 'gutenberg' ),
260 'normal' => __( 'Normal', 'gutenberg' ),
261 'medium' => __( 'Medium', 'gutenberg' ),
262 'large' => __( 'Large', 'gutenberg' ),
263 'huge' => __( 'Huge', 'gutenberg' ),
264 );
265 if ( ! empty( $config['settings'][ $all_blocks ]['typography']['fontSizes'] ) ) {
266 foreach ( $config['settings'][ $all_blocks ]['typography']['fontSizes'] as $font_size_key => $font_size ) {
267 $config['settings'][ $all_blocks ]['typography']['fontSizes'][ $font_size_key ]['name'] = $default_font_sizes_i18n[ $font_size['slug'] ];
268 }
269 }
270 // End i18n logic to remove when JSON i18 strings are extracted.
271
272 self::$core = new WP_Theme_JSON( $config );
273
274 return self::$core;
275 }
276
277 /**
278 * Returns the theme's data.
279 *
280 * Data from theme.json can be augmented via the
281 * $theme_support_data variable. This is useful, for example,
282 * to backfill the gaps in theme.json that a theme has declared
283 * via add_theme_supports.
284 *
285 * Note that if the same data is present in theme.json
286 * and in $theme_support_data, the theme.json's is not overwritten.
287 *
288 * @param array $theme_support_data Theme support data in theme.json format.
289 *
290 * @return WP_Theme_JSON Entity that holds theme data.
291 */
292 public static function get_theme_data( $theme_support_data = array() ) {
293 if ( null === self::$theme ) {
294 $theme_json_data = self::read_json_file( self::get_file_path_from_theme( 'experimental-theme.json' ) );
295 $theme_json_data = self::translate( $theme_json_data, wp_get_theme()->get( 'TextDomain' ) );
296 self::$theme = new WP_Theme_JSON( $theme_json_data );
297 }
298
299 if ( empty( $theme_support_data ) ) {
300 return self::$theme;
301 }
302
303 /*
304 * We want the presets and settings declared in theme.json
305 * to override the ones declared via add_theme_support.
306 */
307 $with_theme_supports = new WP_Theme_JSON( $theme_support_data );
308 $with_theme_supports->merge( self::$theme );
309
310 return $with_theme_supports;
311 }
312
313 /**
314 * Returns the CPT that contains the user's origin config
315 * for the current theme or a void array if none found.
316 *
317 * It can also create and return a new draft CPT.
318 *
319 * @param bool $should_create_cpt Whether a new CPT should be created if no one was found.
320 * False by default.
321 * @param array $post_status_filter Filter CPT by post status.
322 * ['publish'] by default, so it only fetches published posts.
323 *
324 * @return array Custom Post Type for the user's origin config.
325 */
326 private static function get_user_data_from_custom_post_type( $should_create_cpt = false, $post_status_filter = array( 'publish' ) ) {
327 $user_cpt = array();
328 $post_type_filter = 'wp_global_styles';
329 $post_name_filter = 'wp-global-styles-' . urlencode( wp_get_theme()->get_stylesheet() );
330 $recent_posts = wp_get_recent_posts(
331 array(
332 'numberposts' => 1,
333 'orderby' => 'date',
334 'order' => 'desc',
335 'post_type' => $post_type_filter,
336 'post_status' => $post_status_filter,
337 'name' => $post_name_filter,
338 )
339 );
340
341 if ( is_array( $recent_posts ) && ( count( $recent_posts ) === 1 ) ) {
342 $user_cpt = $recent_posts[0];
343 } elseif ( $should_create_cpt ) {
344 $cpt_post_id = wp_insert_post(
345 array(
346 'post_content' => '{}',
347 'post_status' => 'publish',
348 'post_type' => $post_type_filter,
349 'post_name' => $post_name_filter,
350 ),
351 true
352 );
353 $user_cpt = get_post( $cpt_post_id, ARRAY_A );
354 }
355
356 return $user_cpt;
357 }
358
359 /**
360 * Returns the user's origin config.
361 *
362 * @return WP_Theme_JSON Entity that holds user data.
363 */
364 public static function get_user_data() {
365 if ( null !== self::$user ) {
366 return self::$user;
367 }
368
369 $config = array();
370 $user_cpt = self::get_user_data_from_custom_post_type();
371 if ( array_key_exists( 'post_content', $user_cpt ) ) {
372 $decoded_data = json_decode( $user_cpt['post_content'], true );
373
374 $json_decoding_error = json_last_error();
375 if ( JSON_ERROR_NONE !== $json_decoding_error ) {
376 error_log( 'Error when decoding user schema: ' . json_last_error_msg() );
377 return $config;
378 }
379
380 // Very important to verify if the flag isGlobalStylesUserThemeJSON is true.
381 // If is not true the content was not escaped and is not safe.
382 if (
383 is_array( $decoded_data ) &&
384 isset( $decoded_data['isGlobalStylesUserThemeJSON'] ) &&
385 $decoded_data['isGlobalStylesUserThemeJSON']
386 ) {
387 unset( $decoded_data['isGlobalStylesUserThemeJSON'] );
388 $config = $decoded_data;
389 }
390 }
391 self::$user = new WP_Theme_JSON( $config );
392
393 return self::$user;
394 }
395
396 /**
397 * There are three sources of data (origins) for a site:
398 * core, theme, and user. The user's has higher priority
399 * than the theme's, and the theme's higher than core's.
400 *
401 * Unlike the getters {@link get_core_data},
402 * {@link get_theme_data}, and {@link get_user_data},
403 * this method returns data after it has been merged
404 * with the previous origins. This means that if the same piece of data
405 * is declared in different origins (user, theme, and core),
406 * the last origin overrides the previous.
407 *
408 * For example, if the user has set a background color
409 * for the paragraph block, and the theme has done it as well,
410 * the user preference wins.
411 *
412 * @param array $theme_support_data Existing block editor settings.
413 * Empty array by default.
414 * @param string $origin To what level should we merge data.
415 * Valid values are 'theme' or 'user'.
416 * Default is 'user'.
417 *
418 * @return WP_Theme_JSON
419 */
420 public static function get_merged_data( $theme_support_data = array(), $origin = 'user' ) {
421 if ( 'theme' === $origin ) {
422 $result = new WP_Theme_JSON();
423 $result->merge( self::get_core_data() );
424 $result->merge( self::get_theme_data( $theme_support_data ) );
425 return $result;
426 }
427
428 $result = new WP_Theme_JSON();
429 $result->merge( self::get_core_data() );
430 $result->merge( self::get_theme_data( $theme_support_data ) );
431 $result->merge( self::get_user_data() );
432 return $result;
433 }
434
435 /**
436 * Registers a Custom Post Type to store the user's origin config.
437 */
438 public static function register_user_custom_post_type() {
439 $args = array(
440 'label' => __( 'Global Styles', 'gutenberg' ),
441 'description' => 'CPT to store user design tokens',
442 'public' => false,
443 'show_ui' => false,
444 'show_in_rest' => true,
445 'rest_base' => '__experimental/global-styles',
446 'capabilities' => array(
447 'read' => 'edit_theme_options',
448 'create_posts' => 'edit_theme_options',
449 'edit_posts' => 'edit_theme_options',
450 'edit_published_posts' => 'edit_theme_options',
451 'delete_published_posts' => 'edit_theme_options',
452 'edit_others_posts' => 'edit_theme_options',
453 'delete_others_posts' => 'edit_theme_options',
454 ),
455 'map_meta_cap' => true,
456 'supports' => array(
457 'editor',
458 'revisions',
459 ),
460 );
461 register_post_type( 'wp_global_styles', $args );
462 }
463
464 /**
465 * Returns the ID of the custom post type
466 * that stores user data.
467 *
468 * @return integer
469 */
470 public static function get_user_custom_post_type_id() {
471 if ( null !== self::$user_custom_post_type_id ) {
472 return self::$user_custom_post_type_id;
473 }
474
475 $user_cpt = self::get_user_data_from_custom_post_type( true );
476 if ( array_key_exists( 'ID', $user_cpt ) ) {
477 self::$user_custom_post_type_id = $user_cpt['ID'];
478 }
479
480 return self::$user_custom_post_type_id;
481 }
482
483 /**
484 * Whether the current theme has a theme.json file.
485 *
486 * @return boolean
487 */
488 public static function theme_has_support() {
489 if ( ! isset( self::$theme_has_support ) ) {
490 self::$theme_has_support = (bool) self::get_file_path_from_theme( 'experimental-theme.json' );
491 }
492
493 return self::$theme_has_support;
494 }
495
496 /**
497 * Builds the path to the given file
498 * and checks that it is readable.
499 *
500 * If it isn't, returns an empty string,
501 * otherwise returns the whole file path.
502 *
503 * @param string $file_name Name of the file.
504 * @return string The whole file path or empty if the file doesn't exist.
505 */
506 private static function get_file_path_from_theme( $file_name ) {
507 // This used to be a locate_template call.
508 // However, that method proved problematic
509 // due to its use of constants (STYLESHEETPATH)
510 // that threw errors in some scenarios.
511 //
512 // When the theme.json merge algorithm properly supports
513 // child themes, this should also fallback
514 // to the template path, as locate_template did.
515 $located = '';
516 $candidate = get_stylesheet_directory() . '/' . $file_name;
517 if ( is_readable( $candidate ) ) {
518 $located = $candidate;
519 }
520 return $located;
521 }
522
523 }
524