parser = $parser; $this->service = $service; } public function register(): void { add_action( 'admin_menu', [ $this, 'add_menu' ] ); add_action( 'admin_enqueue_scripts', [ $this, 'render_menu_icon_style' ] ); add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] ); add_action( 'admin_enqueue_scripts', [ $this, 'render_theme_preflight' ] ); // The footer is left as WordPress prints it (version on the right). add_action( 'save_post', [ $this, 'clear_font_faces_cache_on_save' ] ); foreach ( $this->ajax_action_names() as $action ) { add_action( 'wp_ajax_v4studio_' . $action, [ $this, 'ajax_' . $action ] ); } } private function ajax_action_names(): array { return [ 'reset_design_system', 'add_missing_defaults', 'export_bundle', 'import_bundle', 'verify_design_system', 'check_class_drift', 'restore_class_definitions', 'keep_elementor_classes', 'review_class_updates', 'update_classes', 'undo_class_update', 'save_dynamic_data', 'dismiss_backup_notice', ]; } private function is_plugin_admin_screen(): bool { $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; $page = $this->get_admin_page_param(); return 'v4studio' === $page || ( $screen && 'toplevel_page_v4studio' === $screen->id ); } public function add_menu(): void { $menu_name = __( 'V4 Studio', 'v4studio' ); $this->page_hook = add_menu_page( $menu_name, $menu_name, 'manage_options', 'v4studio', [ $this, 'render' ], V4STUDIO_URL . 'assets/v4-icon.svg', 58 ); } /** * The menu icon is tinted with a CSS mask, so it follows the admin colour scheme. It loads on * every admin screen because the menu does, and goes through the enqueue API like any other * stylesheet. One array entry per line of CSS: plain strings, because the WordPress.org * guidelines do not allow HEREDOC or NOWDOC. */ public function render_menu_icon_style(): void { $css = sprintf( implode( "\n", [ ':root {', ' --v4studio-admin-menu-icon: #f3f1f1;', ' --v4studio-admin-menu-icon-active: #fff;', '}', '', '#adminmenu .toplevel_page_v4studio .wp-menu-image img {', ' display: none;', '}', '', '#adminmenu .toplevel_page_v4studio .wp-menu-image::before {', ' content: "";', ' display: block;', ' width: 20px;', ' height: 20px;', ' margin: 7px auto 0;', ' padding: 0;', ' background: var(--v4studio-admin-menu-icon);', ' opacity: 1;', ' -webkit-mask: url(\'%1$s\') center / contain no-repeat;', ' mask: url(\'%1$s\') center / contain no-repeat;', '}', '', '#adminmenu .toplevel_page_v4studio:hover .wp-menu-image::before,', '#adminmenu .toplevel_page_v4studio.current .wp-menu-image::before,', '#adminmenu .toplevel_page_v4studio.wp-has-current-submenu .wp-menu-image::before {', ' background: var(--v4studio-admin-menu-icon-active);', '}', ] ), esc_url( V4STUDIO_URL . 'assets/v4-icon.svg' ) ); wp_register_style( 'v4studio-admin-menu-icon', false, [], V4STUDIO_VERSION ); wp_enqueue_style( 'v4studio-admin-menu-icon' ); wp_add_inline_style( 'v4studio-admin-menu-icon', $css ); } public function enqueue_assets( string $hook ): void { if ( ! $this->is_plugin_admin_screen() && $hook !== $this->page_hook ) { return; } /* * URL and version both come from the SAME resolved path. Deriving them separately is * how a cache-busting suffix ends up describing a file that is not the one served. */ $style = \V4STUDIO\Asset_Path::shipped_asset( 'assets/admin.css' ); $script = \V4STUDIO\Asset_Path::shipped_asset( 'assets/admin.js' ); /* * Unpacked into scalars BEFORE the call, deliberately, so the dependency array is the * first [...] in the call and these lines stay greppable. */ $style_url = $style['url']; $style_ver = $style['version']; $script_url = $script['url']; $script_ver = $script['version']; wp_enqueue_style( 'v4studio-admin', $style_url, [], $style_ver ); wp_enqueue_media(); wp_enqueue_script( 'v4studio-admin', $script_url, [ 'jquery', 'media-editor', 'media-views', 'wp-i18n' ], $script_ver, true ); wp_set_script_translations( 'v4studio-admin', 'v4studio' ); $this->enqueue_brand_data_assets(); $this->enqueue_admin_nav_assets(); $this->enqueue_class_update_assets(); // The Tokens screen's rows, fonts and save token are in its own v4studioTokens (Tokens_Screen). wp_localize_script( 'v4studio-admin', 'v4studioAdmin', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'nonces' => $this->ajax_nonces(), 'i18n' => [ 'loading' => __( 'Working...', 'v4studio' ), 'saved' => __( 'Saved.', 'v4studio' ), 'requestFailed' => __( 'Request failed.', 'v4studio' ), 'chooseMedia' => __( 'Choose Media', 'v4studio' ), 'useMedia' => __( 'Use This Media', 'v4studio' ), 'keepElementor' => __( 'Keep Elementor\'s Version', 'v4studio' ), 'restore' => __( 'Restore', 'v4studio' ), /* translators: %s: comma-separated class names. */ 'keepConfirm' => __( 'Keep Elementor\'s version of %s? What was removed in Elementor is removed from V4 Studio\'s copy too, and the backup stylesheet stops serving it. Every other class is left as it is.', 'v4studio' ), 'kept' => __( 'Kept.', 'v4studio' ), 'keepFailed' => __( 'Could not keep Elementor\'s version.', 'v4studio' ), 'keepFailedNothing' => __( 'Could not keep Elementor\'s version. Nothing was changed.', 'v4studio' ), /* translators: %s: a class name. */ 'restoreConfirmOne' => __( 'Replace %s in Elementor with V4 Studio\'s version? Changes made to this class in Elementor will be lost. Every other class is left as it is.', 'v4studio' ), /* translators: %s: comma-separated class names. */ 'restoreConfirm' => __( 'Replace %s in Elementor with V4 Studio\'s version? Changes made to these classes in Elementor will be lost. Every other class is left as it is.', 'v4studio' ), 'restored' => __( 'Restored.', 'v4studio' ), 'restoreFailed' => __( 'Could not restore the classes.', 'v4studio' ), 'restoreFailedNothing' => __( 'Could not restore the classes. Nothing was changed.', 'v4studio' ), 'darkMode' => __( 'Dark mode', 'v4studio' ), 'toLight' => __( 'Switch to light mode', 'v4studio' ), 'toDark' => __( 'Switch to dark mode', 'v4studio' ), 'genericFailed' => __( 'Something went wrong. Nothing was changed.', 'v4studio' ), 'comparing' => __( 'Comparing class values with V4 Studio\'s definition...', 'v4studio' ), 'compareFailed' => __( 'Could not compare the class values.', 'v4studio' ), 'restoreAllConfirm' => __( 'Restore every class to the version V4 Studio ships with? Changes made to these classes in Elementor will be replaced.', 'v4studio' ), 'classesRestored' => __( 'Classes restored.', 'v4studio' ), 'defaultsAdded' => __( 'Missing defaults added.', 'v4studio' ), 'defaultsFailed' => __( 'Could not add the missing defaults.', 'v4studio' ), 'verifyFailed' => __( 'Could not verify.', 'v4studio' ), 'noFile' => __( 'No file selected', 'v4studio' ), 'preparingExport' => __( 'Preparing export...', 'v4studio' ), 'exportFailed' => __( 'Export failed.', 'v4studio' ), 'chooseFile' => __( 'Choose a JSON export file first.', 'v4studio' ), 'importConfirm' => __( 'Apply the values in this file to Elementor now? Values that do not pass the checks are left out.', 'v4studio' ), 'readingFile' => __( 'Reading file...', 'v4studio' ), 'readFailed' => __( 'Could not read this file.', 'v4studio' ), 'importing' => __( 'Importing...', 'v4studio' ), 'imported' => __( 'Imported.', 'v4studio' ), 'importFailed' => __( 'Import failed.', 'v4studio' ), 'unsaved' => __( 'Unsaved changes', 'v4studio' ), 'brandResetFailed' => __( 'Brand Data could not be reset.', 'v4studio' ), 'brandReset' => __( 'Brand Data restored to the V4 Studio defaults.', 'v4studio' ), ], ] ); } /** * Applies the saved light or dark theme before the screen paints, so the page does not flash * the other theme first. Both parts are enqueued in the head: the script must run before the * body renders, and the stylesheet keeps the wrap hidden until the script marks it ready. * One array entry per line, as in render_menu_icon_style(). */ public function render_theme_preflight(): void { if ( ! $this->is_plugin_admin_screen() ) { return; } $css = implode( "\n", [ ':root {', ' --v4studio-pre-dark-bg: #080d15;', ' --v4studio-pre-dark-text: #dce3f0;', ' --v4studio-pre-dark-panel: #111821;', ' --v4studio-pre-dark-border: #202838;', ' --v4studio-pre-light-bg: #f0f0f1;', ' --v4studio-pre-light-text: #1d2327;', '}', '', 'html:not(.v4studio-theme-ready) .v4studio-wrap {', ' visibility: hidden !important;', '}', '', 'html.v4studio-pre-dark,', 'html.v4studio-pre-dark body,', 'html.v4studio-pre-dark #wpwrap,', 'html.v4studio-pre-dark #wpcontent,', 'html.v4studio-pre-dark #wpbody,', 'html.v4studio-pre-dark #wpbody-content {', ' background: var(--v4studio-pre-dark-bg) !important;', ' color: var(--v4studio-pre-dark-text);', '}', '', 'html.v4studio-pre-light,', 'html.v4studio-pre-light body,', 'html.v4studio-pre-light #wpwrap,', 'html.v4studio-pre-light #wpcontent,', 'html.v4studio-pre-light #wpbody,', 'html.v4studio-pre-light #wpbody-content {', ' background: var(--v4studio-pre-light-bg) !important;', ' color: var(--v4studio-pre-light-text);', '}', '', 'html.v4studio-pre-dark .v4studio-wrap {', ' color: var(--v4studio-pre-dark-text);', '}', '', 'html.v4studio-pre-dark .v4studio-header,', 'html.v4studio-pre-dark .v4studio-tool-card {', ' border-color: var(--v4studio-pre-dark-border) !important;', ' background: var(--v4studio-pre-dark-panel) !important;', ' color: var(--v4studio-pre-dark-text) !important;', '}', '', 'html.v4studio-pre-light .v4studio-wrap {', ' color: var(--v4studio-pre-light-text);', '}', ] ); $js = implode( "\n", [ '(function () {', " var savedTheme = '';", '', ' try {', " savedTheme = window.localStorage ? localStorage.getItem('v4studioTheme') : '';", " if ('dark' !== savedTheme && 'light' !== savedTheme) {", " savedTheme = 'dark';", ' }', ' } catch (error) {}', '', " document.documentElement.classList.add('light' === savedTheme ? 'v4studio-pre-light' : 'v4studio-pre-dark');", '', " window.addEventListener('load', function () {", ' window.setTimeout(function () {', " document.documentElement.classList.add('v4studio-theme-ready');", ' }, 500);', ' });', '}());', ] ); wp_register_style( 'v4studio-theme-preflight', false, [], V4STUDIO_VERSION ); wp_enqueue_style( 'v4studio-theme-preflight' ); wp_add_inline_style( 'v4studio-theme-preflight', $css ); wp_register_script( 'v4studio-theme-preflight', false, [], V4STUDIO_VERSION, false ); wp_enqueue_script( 'v4studio-theme-preflight' ); wp_add_inline_script( 'v4studio-theme-preflight', $js ); } public function render(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You do not have permission to access this page.', 'v4studio' ) ); } $this->tidy_staged_import(); $settings = Plugin::get_settings(); /* * Other plugins' admin notices are not captured or re-printed here. WordPress prints * them where it always does, core moves the standard ones into this screen, and * admin.js (moveExternalAdminNotices) docks them above it, so this page outputs no * markup it did not escape itself. */ ?>

<?php esc_attr_e( 'V4 Studio', 'v4studio' ); ?>

render_nav_toggle(); ?>
service->atomic_editor_active() ? null : $this->fallback_retirement_notice(); ?>

>

render(); ?> render_classes_card(); ?>
render_dynamic_data_panel( $settings[ Brand_Data::SETTINGS_KEY ] ?? [] ); ?>
render_import_export_panel(); ?>
import_export_sections(); ?>

$label ) : ?>

$label ) : ?>

service->atomic_editor_active(); $stamp = (array) ( $settings['last_import'][ Fallback_Retirement_Gate::STAMP_KEY ] ?? [] ); $this->render_classes_card_view( [ 'class_count' => self::distinct_class_count( (array) ( $settings['fallback_payload']['classes'] ?? [] ) ), // Every action here needs Elementor's atomic editor; while it is off they are shown, disabled, with the reason. 'atomic_off' => $atomic_off, 'stamp' => $stamp, 'changed' => $atomic_off ? 0 : $this->changed_class_count(), 'undo' => $atomic_off ? null : Class_Update_Service::undo_from( get_option( Class_Update_Service::UNDO_OPTION, null ) ), 'missing' => $atomic_off ? [ 'variables' => 0, 'classes' => 0, 'empty' => 0 ] : $this->missing_default_counts(), // After a Verify that failed only because classes were changed in Elementor (see elementor_removals_offer()). 'removals' => $atomic_off ? null : $this->elementor_removals_offer( $stamp ), 'now' => time(), ] ); } /** * Which of the card's states applies (the first that matches): unavailable, missing, changes, updated, attention, ok. * * @param array $state render_classes_card_view()'s state. */ private function classes_card_state( array $state ): string { $stamp = (array) $state['stamp']; $undo = $state['undo']; if ( ! empty( $state['atomic_off'] ) ) { return 'unavailable'; } if ( ! empty( $stamp ) && empty( $stamp['ok'] ) && (int) ( $stamp['classes_missing'] ?? 0 ) > 0 ) { return 'missing'; } if ( (int) $state['changed'] > 0 ) { return 'changes'; } if ( is_array( $undo ) && (int) $state['now'] - (int) ( $undo['time'] ?? 0 ) < DAY_IN_SECONDS ) { return 'updated'; } if ( ! empty( $stamp ) && empty( $stamp['ok'] ) ) { return 'attention'; } return 'ok'; } /** * The classes card and its Details dialog, from their state, so every state can be drawn and tested. * * @param array{class_count:int,atomic_off:bool,stamp:array,changed:int,undo:?array,missing:array,removals:?array,now:int} $state */ private function render_classes_card_view( array $state ): void { $v4studio_card = $this->classes_card_state( $state ); $v4studio_count = (int) $state['class_count']; $v4studio_stamp = (array) $state['stamp']; $v4studio_changed = (int) $state['changed']; $v4studio_undo = $state['undo']; $v4studio_now = (int) $state['now']; $v4studio_missing = (int) ( $v4studio_stamp['classes_missing'] ?? 0 ); $v4studio_icon = ''; $v4studio_svg_ok = [ 'span' => [ 'class' => true, 'aria-hidden' => true ], 'svg' => [ 'xmlns' => true, 'viewbox' => true, 'fill' => true, 'stroke' => true, 'stroke-width' => true, 'stroke-linecap' => true, 'stroke-linejoin' => true, 'aria-hidden' => true, 'focusable' => true ], 'path' => [ 'd' => true ], 'circle' => [ 'cx' => true, 'cy' => true, 'r' => true, 'fill' => true, 'stroke' => true ] ]; switch ( $v4studio_card ) { case 'unavailable': $v4studio_pill = [ 'is-error', __( 'Unavailable', 'v4studio' ) ]; $v4studio_line = Elementor_Design_System_Service::atomic_editor_off_message(); break; case 'missing': /* translators: %d: number of classes. */ $v4studio_pill = [ 'is-error', sprintf( __( '%d missing', 'v4studio' ), $v4studio_missing ) ]; /* translators: %d: number of classes. */ $v4studio_line = sprintf( _n( '%d shipped class is missing from Elementor.', '%d shipped classes are missing from Elementor.', $v4studio_missing, 'v4studio' ), $v4studio_missing ); break; case 'changes': /* translators: %d: number of classes. */ $v4studio_pill = [ 'is-warning', sprintf( _n( '%d change available', '%d changes available', $v4studio_changed, 'v4studio' ), $v4studio_changed ) ]; /* translators: %d: number of classes. */ $v4studio_line = sprintf( _n( 'This version changes %d class on this site. Classes you changed yourself are kept.', 'This version changes %d classes on this site. Classes you changed yourself are kept.', $v4studio_changed, 'v4studio' ), $v4studio_changed ); break; case 'updated': $v4studio_updated = count( (array) $v4studio_undo['classes'] ); $v4studio_ago = $v4studio_now - (int) $v4studio_undo['time'] < MINUTE_IN_SECONDS ? __( 'just now', 'v4studio' ) /* translators: %s: how long ago, such as "2 hours". */ : sprintf( __( '%s ago', 'v4studio' ), human_time_diff( (int) $v4studio_undo['time'], $v4studio_now ) ); $v4studio_pill = [ 'is-ok', __( 'Updated', 'v4studio' ) ]; /* translators: 1: number of classes, 2: when, such as "just now" or "2 hours ago". */ $v4studio_line = sprintf( _n( '%1$d class updated %2$s.', '%1$d classes updated %2$s.', $v4studio_updated, 'v4studio' ), $v4studio_updated, $v4studio_ago ); break; case 'attention': $v4studio_pill = [ 'is-warning', __( 'Needs a look', 'v4studio' ) ]; $v4studio_line = __( 'Verify found differences in Elementor. Details has the tools to fix them.', 'v4studio' ); break; default: $v4studio_pill = [ 'is-ok', __( 'Up to date', 'v4studio' ) ]; /* translators: %d: number of classes. */ $v4studio_line = sprintf( _n( '%d class installed in Elementor.', '%d classes installed in Elementor.', $v4studio_count, 'v4studio' ), $v4studio_count ) . ( ! empty( $v4studio_stamp['ok'] ) ? ' ' . __( 'All match.', 'v4studio' ) : '' ); } /* translators: %d: number of classes. */ $v4studio_review = $v4studio_changed > 0 ? sprintf( _n( 'Review %d Change', 'Review %d Changes', $v4studio_changed, 'v4studio' ), $v4studio_changed ) : __( 'Review Changes', 'v4studio' ); // The facts class-updates.js recomputes the state from when an answer changes one. $v4studio_facts = [ 'data-v4studio-classes-count' => (string) $v4studio_count, 'data-v4studio-classes-changed' => (string) $v4studio_changed, 'data-v4studio-classes-missing' => (string) $v4studio_missing, 'data-v4studio-classes-verify' => empty( $v4studio_stamp ) ? 'none' : ( ! empty( $v4studio_stamp['ok'] ) ? 'ok' : 'fail' ), ]; if ( is_array( $v4studio_undo ) && $v4studio_now - (int) ( $v4studio_undo['time'] ?? 0 ) < DAY_IN_SECONDS ) { $v4studio_facts['data-v4studio-classes-undo-count'] = (string) count( (array) $v4studio_undo['classes'] ); $v4studio_facts['data-v4studio-classes-undo-ago'] = $v4studio_now - (int) $v4studio_undo['time'] < MINUTE_IN_SECONDS ? __( 'just now', 'v4studio' ) /* translators: %s: how long ago, such as "2 hours". */ : sprintf( __( '%s ago', 'v4studio' ), human_time_diff( (int) $v4studio_undo['time'], $v4studio_now ) ); } if ( 'unavailable' === $v4studio_card ) { $v4studio_facts['data-v4studio-classes-unavailable'] = ''; } ?>
$v4studio_value ) { echo ' ' . esc_attr( $v4studio_attr ) . '="' . esc_attr( $v4studio_value ) . '"'; } ?> aria-labelledby="v4studio-classes-title">

>

0 ? number_format_i18n( $v4studio_changed ) : __( 'None', 'v4studio' ) ) ); ?>

render_missing_defaults_line( (array) $state['missing'] ); ?>

0, 'classes' => 0, 'empty' => 0 ], $v4studio_missing ); if ( $v4studio_missing['variables'] + $v4studio_missing['classes'] + $v4studio_missing['empty'] <= 0 ) { return; } $v4studio_parts = []; $v4studio_sentence = []; if ( $v4studio_missing['variables'] > 0 ) { /* translators: %d: number of design tokens. */ $v4studio_parts[] = sprintf( _n( '%d token', '%d tokens', $v4studio_missing['variables'], 'v4studio' ), $v4studio_missing['variables'] ); } if ( $v4studio_missing['classes'] > 0 ) { /* translators: %d: number of classes. */ $v4studio_parts[] = sprintf( _n( '%d class', '%d classes', $v4studio_missing['classes'], 'v4studio' ), $v4studio_missing['classes'] ); } if ( ! empty( $v4studio_parts ) ) { $v4studio_sentence[] = sprintf( /* translators: %s: what is missing, such as "2 tokens and 9 classes". */ __( 'Missing on this site: %s.', 'v4studio' ), /* translators: joins two counts, such as "2 tokens" and "9 classes". */ implode( __( ' and ', 'v4studio' ), $v4studio_parts ) ); } if ( $v4studio_missing['empty'] > 0 ) { /* translators: %d: number of classes Elementor stores with no declarations. */ $v4studio_sentence[] = sprintf( _n( '%d class is stored in Elementor without its declarations.', '%d classes are stored in Elementor without their declarations.', $v4studio_missing['empty'], 'v4studio' ), $v4studio_missing['empty'] ); } echo '' . esc_html( implode( ' ', $v4studio_sentence ) ) . ''; } /** * Import and Export offer the same sections: Design Tokens and Brand Data. The tokens key stays * `variables`, the name the backup file uses, so older backups keep reading it; only the label says Tokens. */ private function import_export_sections(): array { return array_merge( [ 'all' => __( 'All', 'v4studio' ), 'variables' => __( 'Design Tokens', 'v4studio' ), ], // Label comes from the Brand Data trait so every screen that exports Brand Data agrees. $this->brand_data_export_section() ); } /** * The shipped variables document, plus every declaration of the current one that V4 Studio does not * ship, unchanged. Reset all uses it so a variable it does not own the value of keeps its place in the * stored source. */ private function keep_unshipped_variables( string $defaults_css, string $current_css ): string { $shipped = $this->shipped_variable_values(); $keep = []; foreach ( (array) ( $this->parser->parse_variables( $current_css )['items'] ?? [] ) as $item ) { $name = (string) ( $item['name'] ?? '' ); if ( '' !== $name && ! isset( $shipped[ $name ] ) ) { $keep[] = "\t" . $name . ': ' . (string) ( $item['value'] ?? '' ) . ';'; } } $close = strrpos( $defaults_css, '}' ); if ( empty( $keep ) || false === $close ) { return $defaults_css; } return rtrim( substr( $defaults_css, 0, $close ) ) . "\n" . implode( "\n", $keep ) . "\n" . substr( $defaults_css, $close ); } public function ajax_reset_design_system(): void { $this->verify_ajax(); $kind = $this->get_posted_key( 'field' ); /* * Brand Data resets through THIS handler rather than through a second one of its own. It * shares nothing with the CSS path below -- no parser, no Elementor write * -- but a site has one "restore what shipped" verb, and splitting that verb across two * endpoints is how the two come to disagree. The values come from Brand_Data::seed_record(), * the same method the installer uses, so there is exactly one definition of them. */ if ( Brand_Data::SETTINGS_KEY === $kind ) { $this->reset_brand_data_to_defaults(); return; } if ( 'variables' !== $kind && 'classes' !== $kind ) { wp_send_json_error( [ 'message' => __( 'Invalid reset target.', 'v4studio' ) ], 400 ); } $css = $this->bundled_default_css( $kind ); if ( '' === $css ) { wp_send_json_error( [ 'message' => __( 'The bundled defaults could not be loaded.', 'v4studio' ) ], 500 ); } /* * Reset all restores the tokens V4 Studio ships and touches nothing else. A variable * it does not ship -- one calculated elsewhere, one the site owner made -- keeps its place in * the stored source and its value in Elementor: it is neither written nor deleted. */ $write = null; if ( 'variables' === $kind ) { $settings = Plugin::get_settings(); $css = $this->keep_unshipped_variables( $css, is_string( $settings['variables_css'] ?? null ) ? $settings['variables_css'] : '' ); } $parsed = 'variables' === $kind ? $this->parser->parse_variables( $css ) : $this->parser->parse_classes( $css ); if ( 'variables' === $kind ) { $shipped = $this->shipped_variable_values(); $write = array_values( array_filter( (array) ( $parsed['items'] ?? [] ), static fn( $item ): bool => is_array( $item ) && isset( $shipped[ (string) ( $item['name'] ?? '' ) ] ) ) ); } /* * The only caller that may adopt existing unmapped records. An operator resetting * Variables to defaults IS the authorisation; nothing else in the product carries it. */ $bootstrap = $this->variables_bootstrap_authority( $kind, null === $write ? $parsed : array_merge( $parsed, [ 'items' => $write ] ) ); $import = $this->import_parsed_items( $kind, $write ?? ( $parsed['items'] ?? [] ), null, $bootstrap ); $this->save_css( $kind, $css, $parsed, $import ); /* * Completion is EARNED, not assumed. "The loop finished" says nothing about whether * Elementor now lists and emits all 120 with the right values, and marking complete on a * partial result would permanently disable the only path that can finish the job. */ if ( null !== $bootstrap ) { $verification = $this->service->verify_design_system_in_elementor( true ); \V4STUDIO\Variable_Bootstrap::complete_if_verified( (int) ( $verification['variables_expected'] ?? 0 ), (int) ( $verification['variables_listed'] ?? 0 ), (int) ( $verification['variables_emitted'] ?? 0 ), (int) ( $verification['variables_verified'] ?? 0 ) ); } wp_send_json_success( [ 'field' => $kind, 'css' => $css, 'parsed' => $parsed, 'import' => $import, 'message' => 'variables' === $kind ? __( 'Variables restored to fresh-install defaults.', 'v4studio' ) : __( 'Classes restored to fresh-install defaults.', 'v4studio' ), ] ); } /** * Add the shipped tokens and classes this site is missing, and change nothing it has. * * This is how an update that ships new defaults reaches a site that installed an earlier version. A * reset is not that route: it rewrites the records it covers, so it would replace changes the site * owner made in Elementor. Here a default is a candidate when its name is absent from the stored * source, or when it is a shipped class the source has and Elementor does not (deleted only in * Elementor), and it is imported with $update_existing = false, so Elementor keeps every record * it already holds, edited or not (an EMPTY record is refilled). * * The stored source gains only what Elementor actually created. A name Elementor already had -- a * class or token the owner made under a name V4 Studio later ships -- is reported as left alone and * stays out of the source, so the fallback stylesheet can never paint the shipped rule over the * owner's own. (The Tokens screen still offers such a token in its section, where adopting it is * the owner's choice.) * * Tokens go first, because new classes can bind new aliases. They are written by the Tokens screen's * own path, write_variable_form_changes(), so ownership is claimed exactly as when a missing token is * added there; classes are created only where missing (add_missing_classes()). Both save through save_css(), which re-earns the * fallback retirement stamp like any save. */ public function ajax_add_missing_defaults(): void { $this->verify_ajax(); $settings = Plugin::get_settings(); if ( '' === trim( (string) ( $settings['variables_css'] ?? '' ) ) || '' === trim( (string) ( $settings['classes_css'] ?? '' ) ) ) { wp_send_json_error( [ 'message' => __( 'V4 Studio has not installed its design system on this site yet, so there is nothing to add to. Nothing was changed.', 'v4studio' ) ], 409 ); } $stacks_before = is_array( $settings[ Font_Stack_Repair::MANIFEST_KEY ] ?? null ) ? $settings[ Font_Stack_Repair::MANIFEST_KEY ] : []; $report = [ 'variables' => $this->add_missing_tokens(), 'classes' => $this->add_missing_classes(), ]; /* * Both writes run the font-stack repair, which brings the fallback of every class V4 Studio manages in * line with its font token. On a site whose stacks went stale (a font token changed on * 1.0) that rewrites classes the owner already had, so the message says so instead of "nothing * you already had was changed". Only declarations that were managed before and now differ count. */ $stacks_after = Plugin::get_settings()[ Font_Stack_Repair::MANIFEST_KEY ] ?? []; $refreshed = 0; foreach ( $stacks_before as $key => $entry ) { $after = is_array( $stacks_after ) && is_array( $stacks_after[ $key ] ?? null ) ? $stacks_after[ $key ] : null; if ( is_array( $entry ) && null !== $after && (string) ( $entry['declaration'] ?? '' ) !== (string) ( $after['declaration'] ?? '' ) ) { $refreshed++; } } $added_tokens = count( $report['variables']['added'] ); $added_classes = count( $report['classes']['added'] ); $repaired = count( $report['classes']['repaired'] ); $left_alone = count( $report['variables']['left_alone'] ) + count( $report['classes']['left_alone'] ); $failed = ! empty( $report['variables']['failed'] ) || ! empty( $report['classes']['failed'] ); if ( 0 === $added_tokens && 0 === $added_classes && 0 === $repaired && 0 === $left_alone && 0 === $refreshed && ! $failed ) { $message = __( 'Nothing to add: this site has every token and class V4 Studio ships.', 'v4studio' ); } else { $parts = []; if ( $added_tokens + $added_classes > 0 ) { $parts[] = sprintf( /* translators: 1: "N tokens", 2: "N classes". */ __( 'Added %1$s and %2$s.', 'v4studio' ), /* translators: %d: number of design tokens added. */ sprintf( _n( '%d token', '%d tokens', $added_tokens, 'v4studio' ), $added_tokens ), /* translators: %d: number of classes added. */ sprintf( _n( '%d class', '%d classes', $added_classes, 'v4studio' ), $added_classes ) ); } if ( $repaired > 0 ) { /* translators: %d: number of classes refilled. */ $parts[] = sprintf( _n( 'Restored %d class Elementor stored without its declarations.', 'Restored %d classes Elementor stored without their declarations.', $repaired, 'v4studio' ), $repaired ); } if ( $refreshed > 0 ) { /* translators: %d: number of font-family declarations updated. */ $parts[] = sprintf( _n( 'Updated %d font fallback stack to match your font tokens; nothing else you already had was changed.', 'Updated %d font fallback stacks to match your font tokens; nothing else you already had was changed.', $refreshed, 'v4studio' ), $refreshed ); } else { $parts[] = __( 'Nothing you already had was changed.', 'v4studio' ); } $message = implode( ' ', $parts ); if ( $left_alone > 0 ) { /* translators: %d: number of names Elementor already had. */ $message .= ' ' . sprintf( _n( '%d name already existed in Elementor and was left as it is.', '%d names already existed in Elementor and were left as they are.', $left_alone, 'v4studio' ), $left_alone ); } if ( $failed ) { $message .= ' ' . __( 'Some could not be added; try again, or check that Elementor is active.', 'v4studio' ); } } $stamp = (array) ( Plugin::get_settings()['last_import'][ Fallback_Retirement_Gate::STAMP_KEY ] ?? [] ); wp_send_json_success( [ 'variables' => $report['variables'], 'classes' => $report['classes'], 'missing' => $this->missing_default_counts(), // The Verify result after the add (save_css() verified again), so the Classes card redraws from it. 'verified' => [ 'ok' => ! empty( $stamp['ok'] ), 'missing' => (int) ( $stamp['classes_missing'] ?? 0 ), 'removals' => $this->elementor_removals_offer( $stamp ), // The same decision Verify answers with, so the backup-stylesheet notice can leave when the backup is off. 'retire' => ! empty( $this->service->fallback_retirement_gate()->decide( Fallback_Retirement_Gate::CONTEXT_FRONTEND )['retire'] ), ], 'message' => $message, ] ); } /** * The shipped items whose name the stored source does not contain, in the order the defaults list them. * * A class is matched by its NAME, not by selector, so a shipped class the site already has is never * a candidate even when this version adds a state or breakpoint to it: that would rewrite a record * the owner may have edited, which is what a reset is for. Every variant of a missing class travels * with it. * * @param string $kind 'variables' or 'classes'. * @param string $current The stored source. * @return array */ private function missing_default_items( string $kind, string $current ): array { $defaults_css = $this->bundled_default_css( $kind ); if ( '' === $defaults_css || '' === trim( $current ) ) { return []; } $parse = 'variables' === $kind ? 'parse_variables' : 'parse_classes'; $defaults = $this->parser->$parse( $defaults_css ); $stored = $this->parser->$parse( $current ); $have = []; foreach ( (array) ( $stored['items'] ?? [] ) as $item ) { $have[ $this->default_item_name( $kind, (array) $item ) ] = true; } return array_values( array_filter( (array) ( $defaults['items'] ?? [] ), fn( $item ): bool => is_array( $item ) && '' !== $this->default_item_name( $kind, $item ) && ! isset( $have[ $this->default_item_name( $kind, $item ) ] ) ) ); } /** * How many shipped tokens and classes Add Missing Defaults would add: names the stored source lacks * and Elementor does not hold either, plus shipped classes the source has and Elementor does not (the * ones Verify reports missing). A name the owner made themselves never keeps the offer up. * * `empty` counts the V4 classes Elementor stores without declarations, which the action refills. * * @return array{variables: int, classes: int, empty: int} */ private function missing_default_counts(): array { $settings = Plugin::get_settings(); $held = [ 'variables' => array_keys( $this->elementor_shipped_models() ), 'classes' => (array) $this->service->get_global_class_labels(), ]; $counts = []; foreach ( [ 'variables', 'classes' ] as $kind ) { $names = []; foreach ( $this->missing_default_items( $kind, (string) ( $settings[ $kind . '_css' ] ?? '' ) ) as $item ) { $names[ $this->default_item_name( $kind, $item ) ] = true; } $counts[ $kind ] = count( array_diff_key( $names, array_flip( $held[ $kind ] ) ) ); } $absent = []; foreach ( $this->elementor_absent_class_items( (string) ( $settings['classes_css'] ?? '' ) ) as $item ) { $absent[ $this->default_item_name( 'classes', $item ) ] = true; } $counts['classes'] += count( $absent ); $empty = []; foreach ( $this->empty_class_items( (string) ( $settings['classes_css'] ?? '' ) ) as $item ) { $empty[ $this->default_item_name( 'classes', $item ) ] = true; } $counts['empty'] = count( $empty ); return $counts; } /** A variable's name, or a class item's class name (shared by its states and breakpoints). */ private function default_item_name( string $kind, array $item ): string { return 'variables' === $kind ? trim( (string) ( $item['name'] ?? '' ) ) : sanitize_html_class( (string) ( $item['class_name'] ?? '' ) ); } /** * Add the shipped tokens missing from the source that Elementor does not hold either. * * @return array{added: string[], left_alone: string[], failed: array} */ private function add_missing_tokens(): array { $current = (string) ( Plugin::get_settings()['variables_css'] ?? '' ); $held = $this->elementor_shipped_models(); $add = []; $entry = [ 'added' => [], 'left_alone' => [], 'failed' => [] ]; foreach ( $this->missing_default_items( 'variables', $current ) as $item ) { $name = $this->default_item_name( 'variables', $item ); if ( isset( $held[ $name ] ) ) { $entry['left_alone'][] = $name; } else { $add[] = [ 'name' => $name, 'value' => trim( (string) ( $item['value'] ?? '' ) ) ]; } } if ( empty( $add ) ) { return $entry; } $names = array_column( $add, 'name' ); $applied = [ 'css' => $this->append_variables_to_root( $current, $add ), 'changed' => $names, 'added' => $names, 'deleted' => [], 'errors' => [], ]; $result = $this->write_variable_form_changes( $current, $applied ); $stored = []; foreach ( (array) ( $this->parser->parse_variables( (string) ( Plugin::get_settings()['variables_css'] ?? '' ) )['items'] ?? [] ) as $item ) { $stored[ (string) ( $item['name'] ?? '' ) ] = true; } // A name the write dropped (Elementor holds it under another owner) was not added. foreach ( $names as $name ) { if ( isset( $stored[ $name ] ) ) { $entry['added'][] = $name; } else { $entry['left_alone'][] = $name; } } $entry['failed'] = array_values( array_filter( (array) ( $result['import']['failed'] ?? [] ), static fn( $failure ): bool => 'collision' !== ( $failure['ownership'] ?? '' ) ) ); return $entry; } /** * Add the shipped classes missing from the source, and create in Elementor the shipped classes the * source has but Elementor does not hold (deleted only in Elementor: what Verify reports missing), * from the source's own definition. Elementor keeps every record it already holds. * * Every rule the source holds is kept as it is; each created class is appended as blocks, @media * context included (save_css() then puts the @media blocks in order, as on every class save). * * @return array{added: string[], left_alone: string[], failed: array} */ private function add_missing_classes(): array { $current = (string) ( Plugin::get_settings()['classes_css'] ?? '' ); $missing = $this->missing_default_items( 'classes', $current ); $repair = $this->empty_class_items( $current ); $absent = $this->elementor_absent_class_items( $current ); $entry = [ 'added' => [], 'repaired' => [], 'left_alone' => [], 'failed' => [] ]; if ( empty( $missing ) && empty( $repair ) && empty( $absent ) ) { return $entry; } try { $import = $this->service->import_classes_verified( array_merge( $missing, $repair, $absent ), false ); } catch ( \Throwable $error ) { $import = $this->failed_import_result( $error ); } $created = array_flip( array_map( 'strval', array_keys( (array) ( $import['class_ids'] ?? [] ) ) ) ); $kept = []; $added = []; $left = []; foreach ( $missing as $item ) { $name = $this->default_item_name( 'classes', $item ); if ( isset( $created[ $name ] ) ) { $kept[] = $item; $added[ $name ] = true; } else { $left[ $name ] = true; } } $repaired = []; foreach ( $repair as $item ) { $name = $this->default_item_name( 'classes', $item ); if ( isset( $created[ $name ] ) ) { $repaired[ $name ] = true; } } // Already in the source, so only Elementor gains them. $recreated = false; foreach ( $absent as $item ) { $name = $this->default_item_name( 'classes', $item ); if ( isset( $created[ $name ] ) ) { $added[ $name ] = true; $recreated = true; } } if ( ! empty( $kept ) ) { $css = $this->append_class_blocks( $current, $kept ); $this->save_css( 'classes', $css, $this->parser->parse_classes( $css ), $import ); } elseif ( ! empty( $repaired ) || $recreated ) { // Nothing new for the source; the refilled or recreated records still re-earn the retirement stamp. $this->save_css( 'classes', $current, $this->parser->parse_classes( $current ), $import ); } return [ 'added' => array_keys( $added ), 'repaired' => array_keys( $repaired ), 'left_alone' => empty( $import['failed'] ) ? array_keys( $left ) : [], 'failed' => array_values( (array) ( $import['failed'] ?? [] ) ), ]; } /** * The stored-source items of V4 classes Elementor has a record for but does not render: stored * with no declarations (or not published). One such record used to keep the whole site on the * fallback stylesheet; Add Missing Defaults refills an * empty record from the site's own definition and leaves every record with declarations alone. * Empty when Elementor cannot be read, so nothing is guessed. * * @return array */ private function empty_class_items( string $current ): array { $labels = $this->service->get_global_class_labels(); $held = $this->service->fallback_retirement_gate()->held_class_labels(); if ( null === $labels || null === $held || '' === trim( $current ) ) { return []; } $empty = array_diff_key( array_flip( $labels ), array_flip( $held ) ); return array_values( array_filter( (array) ( $this->parser->parse_classes( $current )['items'] ?? [] ), fn( $item ): bool => is_array( $item ) && isset( $empty[ $this->default_item_name( 'classes', $item ) ] ) ) ); } /** * The stored-source items of shipped classes Elementor holds no record for: deleted only in Elementor, which * is what Verify reports as missing. Add Missing Defaults creates them from the site's own definition; the * source is not changed. Empty when Elementor cannot be read, so nothing is guessed. * * @return array */ private function elementor_absent_class_items( string $current ): array { $labels = $this->service->get_global_class_labels(); if ( null === $labels || '' === trim( $current ) ) { return []; } $shipped = []; foreach ( (array) ( $this->parser->parse_classes( $this->bundled_default_css( 'classes' ) )['items'] ?? [] ) as $item ) { if ( is_array( $item ) ) { $shipped[ $this->default_item_name( 'classes', $item ) ] = true; } } $held = array_flip( array_map( 'strval', $labels ) ); return array_values( array_filter( (array) ( $this->parser->parse_classes( $current )['items'] ?? [] ), function ( $item ) use ( $shipped, $held ): bool { $name = is_array( $item ) ? $this->default_item_name( 'classes', $item ) : ''; return '' !== $name && isset( $shipped[ $name ] ) && ! isset( $held[ $name ] ); } ) ); } /** * The fallback-retirement condition, when the screen should show it; null while the fallback is retired. * * `V4STUDIO_SHOW_FALLBACK_NOTICE` set to false hides it * (before the fingerprinting, so the default path pays nothing then), and a fallback forced on with the * rollback constant is reported without an action, because re-verifying cannot and should not clear it. * * @return array{reason: string, recoverable: bool}|null */ private function fallback_retirement_notice(): ?array { $show_notice = defined( 'V4STUDIO_SHOW_FALLBACK_NOTICE' ) ? (bool) constant( 'V4STUDIO_SHOW_FALLBACK_NOTICE' ) : true; if ( ! $show_notice ) { return null; } $gate = $this->service->fallback_retirement_gate(); $decision = $gate->decide( \V4STUDIO\Fallback_Retirement_Gate::CONTEXT_FRONTEND ); if ( $gate->rollback_engaged() ) { return [ 'reason' => (string) ( $decision['reason'] ?? '' ), 'recoverable' => false, 'pending' => false, ]; } if ( ! empty( $decision['retire'] ) ) { return null; } $reason = (string) ( $decision['reason'] ?? '' ); // Dismissed for this reason by this administrator: hidden until the reason changes. if ( hash_equals( self::backup_notice_key( $reason ), (string) get_user_meta( get_current_user_id(), self::BACKUP_NOTICE_USER_META, true ) ) ) { return null; } return [ 'reason' => $reason, 'recoverable' => true, 'pending' => Fallback_Reverify::is_pending(), ]; } /** Per-user record of the backup-stylesheet notice this administrator dismissed (its reason's key). */ public const BACKUP_NOTICE_USER_META = 'v4studio_backup_notice_dismissed'; private static function backup_notice_key( string $reason ): string { return hash( 'sha256', $reason ); } /** * Hides the backup-stylesheet notice for this administrator until its reason changes. Changes nothing * else: the backup stays as the gate decides, and Verify Now stays one tab away. */ public function ajax_dismiss_backup_notice(): void { $this->verify_ajax(); $decision = $this->service->fallback_retirement_gate()->decide( \V4STUDIO\Fallback_Retirement_Gate::CONTEXT_FRONTEND ); update_user_meta( get_current_user_id(), self::BACKUP_NOTICE_USER_META, self::backup_notice_key( (string) ( $decision['reason'] ?? '' ) ) ); wp_send_json_success( [] ); } /** * Re-earn the fallback retirement stamp on demand, WITHOUT writing the design system. * * The retirement stamp is pinned to a hash of V4's source and a fingerprint of what Elementor holds. * Anything that changes either side invalidates it, and every other path that re-stamps first pushes * the stored source to Elementor (save, import, reset), which can overwrite edits made in Elementor. * This action only READS both sides, records what it finds and reports the gate's decision. It * changes no class, no variable and no stored CSS; its one write is the stamp itself. * * Honest about failure: re-verifying does not force retirement. A genuinely missing binding produces a * stamp that still refuses to retire, and the response carries the resulting decision either way. * * Administrators only, behind this action's own nonce, and only from an admin AJAX request, so no * frontend, preview or editor request can write the stamp. */ public function ajax_verify_design_system(): void { $this->verify_ajax(); $this->service->clear_elementor_cache(); $stamp = $this->service->verify_and_stamp_fallback_retirement(); $decision = $this->service->fallback_retirement_gate()->decide( \V4STUDIO\Fallback_Retirement_Gate::CONTEXT_FRONTEND ); $retired = ! empty( $decision['retire'] ); wp_send_json_success( [ 'retire' => $retired, 'reason' => (string) ( $decision['reason'] ?? '' ), 'ok' => is_array( $stamp ) && ! empty( $stamp['ok'] ), 'removals' => $retired ? null : $this->elementor_removals_offer( (array) ( $stamp['stamp'] ?? [] ) ), // The Classes card shows "N missing" (and Add Missing) from this, without a reload. 'missing' => $retired ? 0 : (int) ( $stamp['stamp']['classes_missing'] ?? 0 ), 'message' => $retired ? __( 'Verified. Elementor holds the design system, and the fallback stylesheet is off.', 'v4studio' ) : __( 'Checked again: the backup stylesheet is still needed. The reason is shown above.', 'v4studio' ), ] ); } /** * Which V4 Studio classes Elementor holds with different values from V4 Studio's definition. * Information only, and read only: it writes nothing, does not touch the retirement stamp and changes * nothing about the fallback (see Elementor_Design_System_Service::class_value_drift()). It is a request * of its own, sent after Verify, because building every class through Elementor's converter takes * seconds and Verify's own answer should not wait for it. */ public function ajax_check_class_drift(): void { $this->verify_ajax(); $drift = $this->service->class_value_drift(); if ( null === $drift ) { wp_send_json_error( [ 'message' => __( 'Elementor\'s classes could not be read, so their values were not compared.', 'v4studio' ) ], 503 ); } $labels = $drift['labels']; wp_send_json_success( [ 'labels' => $labels, 'checked' => $drift['checked'], 'message' => empty( $labels ) /* translators: %d: number of classes compared. */ ? sprintf( _n( 'The %d class Elementor holds matches V4 Studio\'s definition.', 'All %d classes Elementor holds match V4 Studio\'s definition.', $drift['checked'], 'v4studio' ), $drift['checked'] ) : sprintf( /* translators: 1: number of classes, 2: comma-separated class names. */ _n( '%1$d class differs from V4 Studio\'s definition: %2$s. That is often a change made in Elementor; it is not an error.', '%1$d classes differ from V4 Studio\'s definition: %2$s. That is often a change made in Elementor; it is not an error.', count( $labels ), 'v4studio' ), count( $labels ), implode( ', ', $labels ) ), ] ); } /** * Put V4 Studio's definition back into Elementor for the classes named, and only those. * * A name must be a class in the stored source; anything else is refused before a write. The classes * are written from the site's own stored definition (the one the drift check compared against) * through the verified import, which replaces what Elementor holds for them; every other class is left * alone. The stored source does not change, and the retirement stamp is re-earned as after any write. */ public function ajax_restore_class_definitions(): void { $this->verify_ajax(); $asked = array_values( array_unique( array_filter( array_map( 'sanitize_html_class', array_filter( $this->get_posted_array( 'labels' ), 'is_string' ) ) ) ) ); $source = (array) ( $this->parser->parse_classes( (string) ( Plugin::get_settings()['classes_css'] ?? '' ) )['items'] ?? [] ); $known = []; foreach ( $source as $item ) { $known[ sanitize_html_class( (string) ( $item['class_name'] ?? '' ) ) ] = true; } if ( empty( $asked ) || array_diff( $asked, array_keys( $known ) ) ) { wp_send_json_error( [ 'message' => __( 'That class is not one V4 Studio installed. Nothing was changed.', 'v4studio' ) ], 400 ); } $items = array_values( array_filter( $source, static fn( $item ): bool => in_array( sanitize_html_class( (string) ( $item['class_name'] ?? '' ) ), $asked, true ) ) ); try { $import = $this->service->import_classes_verified( $items, true ); } catch ( \Throwable $error ) { $import = $this->failed_import_result( $error ); } /* * The import replaced those classes' variants, which removes the font fallback stacks V4 Studio manages on them. * Put them back now, telling the repair which variants this import rewrote: otherwise the next save reads the * missing stacks as the owner's deletion, records an opt-out, and the stack stays off (.link-inverse font-family, for one). save_css() does the same for every other class write. */ Plugin::update_settings( $this->repair_font_stacks( Plugin::get_settings(), (array) ( $import['rewritten_variants'] ?? [] ) ) ); $this->service->clear_elementor_cache(); $this->service->verify_and_stamp_fallback_retirement(); if ( ! empty( $import['failed'] ) ) { wp_send_json_error( [ 'message' => __( 'Some classes could not be restored; try again, or check that Elementor is active.', 'v4studio' ), 'import' => $import ], 500 ); } wp_send_json_success( [ 'labels' => $asked, /* translators: %s: comma-separated class names. */ 'message' => sprintf( __( 'Restored V4 Studio\'s version of %s. Every other class was left as it is.', 'v4studio' ), implode( ', ', $asked ) ), ] ); } /** * Accept what Elementor removed, for the classes named and only those: a class deleted in Elementor leaves the * stored source, and a state or property Elementor no longer stores leaves that class's stored rules. Then the * design system is verified and stamped again, so the backup stylesheet turns off when nothing else is wrong. * * The opposite of restore_class_definitions(), which puts V4 Studio's definition back into Elementor. Only * removals Verify reports right now can be kept: Verify runs first, and a name it does not report is refused * before anything is written. Elementor is not written to. */ public function ajax_keep_elementor_classes(): void { $this->verify_ajax(); $asked = array_values( array_unique( array_filter( array_map( 'sanitize_html_class', array_filter( $this->get_posted_array( 'labels' ), 'is_string' ) ) ) ) ); $this->service->clear_elementor_cache(); $verified = $this->service->verify_and_stamp_fallback_retirement(); $removals = (array) ( $verified['stamp']['elementor_removals']['classes'] ?? [] ); if ( empty( $asked ) || array_diff( $asked, array_keys( $removals ) ) ) { wp_send_json_error( [ 'message' => __( 'Elementor holds those classes as V4 Studio has them, so there is nothing to keep. Nothing was changed.', 'v4studio' ) ], 409 ); } $css = (string) ( Plugin::get_settings()['classes_css'] ?? '' ); $kept = array_intersect_key( $removals, array_flip( $asked ) ); $next = Elementor_Design_System_Service::classes_css_without( $css, $kept, $this->parser ); if ( $next !== $css ) { // Saving stamps again: the fallback turns off if these removals were all that kept it on. $this->save_css( 'classes', $next, $this->parser->parse_classes( $next ) ); } $decision = $this->service->fallback_retirement_gate()->decide( \V4STUDIO\Fallback_Retirement_Gate::CONTEXT_FRONTEND ); $retired = ! empty( $decision['retire'] ); wp_send_json_success( [ 'labels' => $asked, 'retire' => $retired, 'reason' => (string) ( $decision['reason'] ?? '' ), 'message' => $retired /* translators: %s: comma-separated class names. */ ? sprintf( __( 'Kept Elementor\'s version of %s. Elementor holds the design system, and the backup stylesheet is off.', 'v4studio' ), implode( ', ', $asked ) ) /* translators: %s: comma-separated class names. */ : sprintf( __( 'Kept Elementor\'s version of %s. The backup stylesheet is still on for another reason; Verify shows it.', 'v4studio' ), implode( ', ', $asked ) ), ] ); } /** * What the Classes card offers to keep or restore after a Verify that failed only because of removals made in * Elementor. Null when there is nothing to offer: Verify passed, failed for another reason as well, or the * stamp predates removal records. * * @return array{labels:string[],descriptions:string[],message:string}|null */ private function elementor_removals_offer( array $stamp ): ?array { $removals = (array) ( $stamp['elementor_removals'] ?? [] ); if ( ! empty( $stamp['ok'] ) || empty( $removals['only'] ) || empty( $removals['classes'] ) ) { return null; } $descriptions = array_values( Elementor_Design_System_Service::describe_elementor_removals( (array) $removals['classes'] ) ); return [ 'labels' => array_map( 'strval', array_keys( (array) $removals['classes'] ) ), 'descriptions' => $descriptions, 'message' => sprintf( /* translators: %s: comma-separated classes, each with what was removed, such as "link-inverse (:focus)". */ __( 'Removed in Elementor: %s. Keep Elementor\'s Version, or Restore to put it back.', 'v4studio' ), implode( ', ', $descriptions ) ), ]; } public function ajax_export_bundle(): void { $this->verify_ajax(); $sections = $this->selected_import_export_sections( $this->get_posted_array( 'sections' ) ); $payload = $this->build_export_payload( $sections ); wp_send_json_success( [ 'filename' => 'v4-studio-for-elementor-export-' . gmdate( 'Y-m-d-His' ) . '.json', 'payload' => $payload, 'summary' => $this->import_export_summary( $payload['data'] ?? [] ), ] ); } public function ajax_import_bundle(): void { $this->verify_ajax(); $raw_payload = $this->get_posted_string( 'payload' ); // The import limit is 10 MB, measured on the sanitised text before it is decoded. if ( strlen( $raw_payload ) > 10 * 1024 * 1024 ) { wp_send_json_error( [ 'message' => __( 'The uploaded JSON file exceeds the 10 MB import limit.', 'v4studio' ) ], 400 ); } if ( '' === trim( $raw_payload ) ) { wp_send_json_error( [ 'message' => __( 'Choose a JSON export file first.', 'v4studio' ) ], 400 ); } $payload = json_decode( $raw_payload, true, 64 ); if ( ! is_array( $payload ) ) { wp_send_json_error( [ 'message' => JSON_ERROR_DEPTH === json_last_error() ? __( 'The uploaded file is nested too deeply to import (more than 64 levels).', 'v4studio' ) : __( 'The uploaded file is not valid JSON.', 'v4studio' ), ], 400 ); } // The import reads two sections, Design Tokens and Brand Data, and the format marker. $payload = $this->import_sections( $payload ); $payload = $this->sanitize_import_payload( $payload ); wp_send_json_success( $this->apply_import_payload( $payload, $this->selected_import_export_sections( $this->get_posted_array( 'sections' ) ) ) ); } /** One request token per operation; authorization remains independent. */ private function ajax_nonces(): array { $nonces = []; foreach ( $this->ajax_action_names() as $action ) { $nonces[ $action ] = wp_create_nonce( 'v4studio_' . $action ); } return $nonces; } private function verify_ajax(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error( [ 'message' => __( 'Administrators only.', 'v4studio' ) ], 403 ); } // Bind the nonce to the registered callback, never to an arbitrary request action. $hook = current_filter(); $prefix = 'wp_ajax_v4studio_'; $action = str_starts_with( $hook, $prefix ) ? substr( $hook, strlen( $prefix ) ) : ''; if ( ! in_array( $action, $this->ajax_action_names(), true ) ) { wp_send_json_error( [ 'message' => __( 'Invalid request.', 'v4studio' ) ], 400 ); } if ( ! is_string( $_POST['nonce'] ?? null ) ) { wp_send_json_error( [ 'message' => __( 'Invalid request token.', 'v4studio' ) ], 403 ); } check_ajax_referer( 'v4studio_' . $action, 'nonce' ); /* * These read or write Elementor's classes and variables, which Elementor registers only while its atomic editor * is on. With it off they could only fail, report misleading differences, or save V4 Studio's source while * Elementor rejected the same change; they answer this instead, before anything is read or written. */ if ( in_array( $action, self::NEEDS_ATOMIC_EDITOR, true ) && false === $this->service->atomic_editor_active() ) { wp_send_json_error( [ 'message' => Elementor_Design_System_Service::atomic_editor_off_message(), 'atomic_editor_off' => true ], 409 ); } // Reject malformed shapes before any domain handler can cast or persist them. foreach ( [ 'payload', 'field', 'rows', 'revision' ] as $key ) { if ( isset( $_POST[ $key ] ) && ! is_scalar( $_POST[ $key ] ) ) { wp_send_json_error( [ 'message' => __( 'Invalid request data.', 'v4studio' ) ], 400 ); } } foreach ( [ 'sections', 'dynamic_data' ] as $key ) { if ( ! isset( $_POST[ $key ] ) ) { continue; } if ( ! is_array( $_POST[ $key ] ) ) { wp_send_json_error( [ 'message' => __( 'Invalid request data.', 'v4studio' ) ], 400 ); } foreach ( $this->get_posted_array( $key ) as $value ) { if ( ! is_scalar( $value ) && null !== $value ) { wp_send_json_error( [ 'message' => __( 'Invalid request data.', 'v4studio' ) ], 400 ); } } } foreach ( [ 'logo_dark', 'logo_light' ] as $key ) { $value = $this->get_posted_array( 'dynamic_data' )[ $key ] ?? null; if ( null !== $value && ( ! is_scalar( $value ) || ( '' !== (string) $value && ! preg_match( '/^[0-9]+$/D', (string) $value ) ) ) ) { wp_send_json_error( [ 'message' => __( 'Invalid media ID.', 'v4studio' ) ], 400 ); } } } private function selected_import_export_sections( $raw_sections ): array { $valid = [ 'variables', 'brand_data' ]; if ( ! is_array( $raw_sections ) ) { $raw_sections = [ $raw_sections ]; } $sections = array_values( array_filter( array_map( static function ( $section ): string { return is_string( $section ) ? sanitize_key( $section ) : ''; }, $raw_sections ) ) ); if ( empty( $sections ) || in_array( 'all', $sections, true ) ) { return $valid; } return array_values( array_intersect( $valid, $sections ) ); } private function build_export_payload( array $sections ): array { $settings = Plugin::get_settings(); $data = []; if ( in_array( 'variables', $sections, true ) ) { $css = is_string( $settings['variables_css'] ?? null ) ? $settings['variables_css'] : $this->default_variables_css(); $parsed = is_array( $settings['last_variables'] ?? null ) ? $settings['last_variables'] : $this->parser->parse_variables( $css ); $data['variables'] = [ 'css' => $css, 'parsed' => $parsed, ]; } if ( in_array( 'brand_data', $sections, true ) ) { $data['brand_data'] = $this->brand_data_export_payload(); } return [ 'schema' => 'v4studio.export.v2', 'plugin' => 'V4 Studio for Elementor', 'version' => V4STUDIO_VERSION, 'exported_at' => gmdate( 'c' ), 'site_url' => home_url(), 'data' => $data, ]; } /** * The import payload, built from what the import reads: Design Tokens (`variables`) and Brand Data * (`brand_data`), from the file's `data` object (or its top level, for a file without one), and the `schema` * marker. A `data` value that is not an object is passed on as it is, so the import refuses the file as invalid. */ private function import_sections( array $payload ): array { $sections = static function ( array $from ): array { $read = []; foreach ( [ 'variables', 'brand_data' ] as $key ) { if ( array_key_exists( $key, $from ) ) { $read[ $key ] = $from[ $key ]; } } return $read; }; $built = array_key_exists( 'schema', $payload ) ? [ 'schema' => $payload['schema'] ] : []; if ( array_key_exists( 'data', $payload ) ) { $built['data'] = is_array( $payload['data'] ) ? $sections( $payload['data'] ) : $payload['data']; return $built; } return $sections( $payload ) + $built; } /** * An export file is untrusted input, and json_decode() only parses it. Every string in it is * cleaned here, before the importer reads anything: the token list with sanitize_css_input(), * every other string -- Brand Data fields, logo descriptors -- stripped of markup. Each value is then * checked again for its own type where it is used: a token value as a typed Design Tokens * value, Brand Data by its sanitizer. Types are kept, so the importer's shape checks still * reject a malformed section. */ private function sanitize_import_payload( array $payload ): array { if ( is_array( $payload['data'] ?? null ) ) { $payload['data'] = $this->sanitize_import_css_sections( $payload['data'] ); } else { $payload = $this->sanitize_import_css_sections( $payload ); } return map_deep( $payload, static function ( $value ) { return is_string( $value ) ? wp_strip_all_tags( $value ) : $value; } ); } /** The Design Tokens section, in either shape extract_import_css() accepts. */ private function sanitize_import_css_sections( array $data ): array { if ( is_string( $data['variables'] ?? null ) ) { $data['variables'] = $this->sanitize_css_input( $data['variables'] ); } elseif ( is_array( $data['variables'] ?? null ) && is_string( $data['variables']['css'] ?? null ) ) { $data['variables']['css'] = $this->sanitize_css_input( $data['variables']['css'] ); } return $data; } /** * Import a backup file: checked values only, applied at once. * * - Variables: each `--name: value` pair in the file becomes a typed row through * variable_import_row() and goes through the same checks as the Tokens screen * (apply_variable_form_rows), then the same write. A value that fits no kind, or that the * checks refuse, is left out and named in the result; the rest are applied. * - Brand Data: staged and applied in the same request through its own sanitiser. * * The import reads these two sections. * * @return array */ private function apply_import_payload( array $payload, array $sections ): array { if ( array_key_exists( 'schema', $payload ) && 'v4studio.export.v2' !== $payload['schema'] ) { wp_send_json_error( [ 'message' => __( 'Unsupported export format.', 'v4studio' ) ], 400 ); } if ( array_key_exists( 'data', $payload ) && ! is_array( $payload['data'] ) ) { wp_send_json_error( [ 'message' => __( 'Invalid export data.', 'v4studio' ) ], 400 ); } $data = is_array( $payload['data'] ?? null ) ? $payload['data'] : $payload; $summary = []; $messages = []; $result = []; if ( in_array( 'variables', $sections, true ) && array_key_exists( 'variables', $data ) ) { $css = $this->extract_import_css( $data['variables'] ); if ( strlen( $css ) > 1024 * 1024 ) { wp_send_json_error( [ 'message' => __( 'The Design Tokens section of this file exceeds the 1 MB limit. Nothing was imported.', 'v4studio' ) ], 400 ); } $variables = $this->import_variable_values( $css ); $summary['variables'] = [ 'applied' => count( $variables['applied'] ), 'unchanged' => $variables['unchanged'], 'rejected' => $variables['rejected'], ]; $messages[] = $this->variable_import_message( $variables ); $result['rows'] = $variables['rows']; $result['revision'] = $variables['revision']; } if ( in_array( 'brand_data', $sections, true ) && array_key_exists( 'brand_data', $data ) ) { $settings = Plugin::get_settings(); $staged = is_array( $settings['staged_import'] ?? null ) ? $settings['staged_import'] : []; $staged = array_intersect_key( $staged, [ 'brand_data' => true ] ); $brand = $this->stage_brand_data_import( $data['brand_data'], $staged ); if ( null !== $brand ) { $settings['staged_import'] = $staged; Plugin::update_settings( $settings ); // The staging summary names what was skipped; the apply step reports what changed. $applied = $this->apply_staged_brand_data(); $summary['brand_data'] = array_merge( $brand, (array) $applied, [ 'applied' => null !== $applied ] ); if ( null !== $applied ) { // The Brand Data panel shows the imported record in place, as after its reset: every field, both logo // thumbnails and the sample note, and saves over it from now on (its new revision). $record = Brand_Data::get(); $result['brand_data'] = [ 'data' => $record, 'previews' => $this->brand_data_logo_previews( $record ), 'samples' => $this->brand_sample_message( $record ), ]; $result = array_merge( $result, Save_Revision::fresh( [ 'brand_data' ] ) ); } } $messages[] = empty( $summary['brand_data'] ) ? __( 'Brand Data: nothing to import.', 'v4studio' ) : __( 'Brand Data imported.', 'v4studio' ); // Name what was left out: the keys only, never their values (the file is untrusted). $skipped = (int) ( $summary['brand_data']['skipped'] ?? 0 ); if ( $skipped > 0 ) { $names = array_map( 'strval', (array) ( $summary['brand_data']['skipped_keys'] ?? [] ) ); $hidden = $skipped - count( $names ); if ( empty( $names ) ) { /* translators: %d: how many Brand Data entries in the file were not recognized. */ $messages[] = sprintf( _n( 'Brand Data: %d entry was not recognized and was left out.', 'Brand Data: %d entries were not recognized and were left out.', $skipped, 'v4studio' ), $skipped ); } elseif ( $hidden > 0 ) { /* translators: 1: the names of the Brand Data entries left out, comma separated; 2: how many more were left out. */ $messages[] = sprintf( __( 'Brand Data entries not recognized and left out: %1$s and %2$d more.', 'v4studio' ), implode( ', ', $names ), $hidden ); } else { /* translators: %s: the names of the Brand Data entries left out, comma separated. */ $messages[] = sprintf( __( 'Brand Data entries not recognized and left out: %s.', 'v4studio' ), implode( ', ', $names ) ); } } } return array_merge( $result, [ 'message' => empty( $messages ) ? __( 'Nothing to import: the file has no content for the selected sections.', 'v4studio' ) : implode( ' ', $messages ), 'summary' => $summary, ] ); } /** * Apply the variable values of an import file through the Tokens screen's checks. * * apply_variable_form_rows() is all or nothing, so a refused row is taken out and the rest * are checked again; each pass removes at least one row, so this ends. * * @return array{applied:string[],unchanged:int,rejected:array,rows:array,revision:string,import:mixed} */ private function import_variable_values( string $file_css ): array { $current = (string) ( Plugin::get_settings()['variables_css'] ?? '' ); $plan = $this->plan_variable_import( $file_css, $current ); $settled = $this->settle_variable_import_rows( $current, $plan['rows'] ); $result = [ 'applied' => [], 'unchanged' => $plan['unchanged'], 'rejected' => array_merge( $plan['rejected'], $settled['rejected'] ), 'rows' => [], 'revision' => $this->variables_revision( $current ), 'import' => null, ]; if ( null !== $settled['applied'] ) { $written = $this->write_variable_form_changes( $current, $settled['applied'] ); $result['applied'] = $settled['applied']['changed']; $result['rows'] = $written['rows']; $result['revision'] = $written['revision']; $result['import'] = $written['import']; } if ( empty( $result['rows'] ) ) { $result['rows'] = $this->variable_form_rows( $current ); } return $result; } /** * Turn the file's declarations into typed rows. Values equal to the stored ones are skipped. * * @return array{rows:array>,unchanged:int,rejected:array} */ private function plan_variable_import( string $file_css, string $current_css ): array { $current = []; foreach ( (array) ( $this->parser->parse_variables( $current_css )['items'] ?? [] ) as $item ) { $current[ (string) ( $item['name'] ?? '' ) ] = trim( (string) ( $item['value'] ?? '' ) ); } $rows = []; $rejected = []; $unchanged = 0; $seen = []; foreach ( (array) ( $this->parser->parse_variables( $file_css )['items'] ?? [] ) as $item ) { $name = trim( (string) ( $item['name'] ?? '' ) ); $value = trim( (string) ( $item['value'] ?? '' ) ); if ( '' === $name || isset( $seen[ $name ] ) ) { continue; } $seen[ $name ] = true; if ( isset( $current[ $name ] ) && $current[ $name ] === $value ) { ++$unchanged; continue; } $row = preg_match( '/^--[a-z0-9_-]+$/', $name ) ? $this->variable_import_row( $name, $value, isset( $current[ $name ] ) ) : null; if ( null === $row ) { $rejected[] = [ 'name' => $name, 'message' => __( 'This value is not a color, size, font, number or variable reference V4 Studio can save.', 'v4studio' ) ]; continue; } $rows[] = $row; } return [ 'rows' => $rows, 'unchanged' => $unchanged, 'rejected' => $rejected ]; } /** The typed row for one imported value, or null when the value fits no editable kind. */ private function variable_import_row( string $name, string $value, bool $exists ): ?array { $model = Design_Token_Value::describe( $value ); $row = [ 'op' => $exists ? 'set' : 'add', 'name' => $name, 'kind' => $model['kind'] ]; switch ( $model['kind'] ) { case 'color': case 'number': return $row + [ 'value' => $model['value'] ]; case 'font': return $row + [ 'family' => $model['family'], 'generic' => $model['generic'] ]; case 'alias': return $row + [ 'target' => $model['target'] ]; case 'size': // A value on another View Port keeps it, so its curve is not changed on the way in. if ( 'fluid' === $model['mode'] ) { return $row + array_intersect_key( $model, array_flip( [ 'mode', 'min', 'max', 'vmin', 'vmax' ] ) ); } if ( 'fixed' === $model['mode'] ) { return $row + [ 'mode' => 'fixed', 'number' => $model['number'], 'unit' => $model['unit'] ]; } if ( 'expression' === $model['mode'] ) { return $row + [ 'mode' => 'expression', 'value' => $model['value'] ]; } } return null; } /** * Check the rows, dropping each one the checks refuse, until the rest pass together. * * @return array{applied:?array,rejected:array} */ private function settle_variable_import_rows( string $current_css, array $rows ): array { $rejected = []; while ( ! empty( $rows ) ) { $applied = $this->apply_variable_form_rows( $current_css, $rows ); if ( empty( $applied['errors'] ) ) { return [ 'applied' => empty( $applied['changed'] ) && empty( $applied['deleted'] ) ? null : $applied, 'rejected' => $rejected ]; } $refused = array_column( $applied['errors'], 'message', 'name' ); $kept = []; foreach ( $rows as $row ) { $key = '--' . ltrim( sanitize_key( ltrim( (string) $row['name'], '-' ) ), '-' ); if ( isset( $refused[ $key ] ) ) { $rejected[] = [ 'name' => (string) $row['name'], 'message' => (string) $refused[ $key ] ]; } else { $kept[] = $row; } } if ( count( $kept ) === count( $rows ) ) { // An error no row can be blamed for: refuse them all rather than loop. foreach ( $rows as $row ) { $rejected[] = [ 'name' => (string) $row['name'], 'message' => __( 'This value could not be applied.', 'v4studio' ) ]; } break; } $rows = $kept; } return [ 'applied' => null, 'rejected' => $rejected ]; } /** @param array{applied:string[],unchanged:int,rejected:array} $result */ private function variable_import_message( array $result ): string { $applied = count( $result['applied'] ); $rejected = count( $result['rejected'] ); $message = 0 === $applied ? __( 'Design Tokens: no values changed.', 'v4studio' ) : sprintf( /* translators: %d: number of variables. */ _n( 'Design Tokens: %d value applied to Elementor.', 'Design Tokens: %d values applied to Elementor.', $applied, 'v4studio' ), $applied ); if ( $rejected > 0 ) { $message .= ' ' . sprintf( /* translators: %d: number of variables. */ _n( '%d value was left out; see the list below.', '%d values were left out; see the list below.', $rejected, 'v4studio' ), $rejected ); } return $message; } /** The staging key holds Brand Data only; any other entry in it is removed from the settings. */ private function tidy_staged_import(): void { $settings = Plugin::get_settings(); $staged = $settings['staged_import'] ?? null; if ( ! is_array( $staged ) || array_keys( $staged ) === array_keys( array_intersect_key( $staged, [ 'brand_data' => true ] ) ) ) { return; } $settings['staged_import'] = array_intersect_key( $staged, [ 'brand_data' => true ] ); Plugin::update_settings( $settings ); } private function import_export_summary( array $data ): array { if ( ! isset( $data['variables'] ) ) { return []; } return [ 'variables' => count( $this->parser->parse_variables( $this->extract_import_css( $data['variables'] ) )['items'] ?? [] ) ]; } }