parser = $parser; $this->service = $service; } /** * Priority 15: AFTER Elementor's database migrations. * * This used to be 5, and on a genuinely fresh installation that made the first admin request * unable to import a single class. Elementor gates PUT /elementor/v1/global-classes on * `current_user_can( Add_Capabilities::UPDATE_CLASS )` -- a CUSTOM capability * (`elementor_global_classes_update_class`) that does not exist until Elementor's * Global_Classes_Database_Updater migration grants it to the administrator role. That updater * registers on `admin_init` at the default priority 10, so at priority 5 V4 ran first, the * capability did not yet exist, and every class write came back * "Sorry, you are not allowed to do that." * * Variables were unaffected and written fine, which is what made the symptom confusing: their * routes are gated on `is_user_logged_in()`, not on the migration-granted capability. So a * fresh site ended up with 132 variables, zero classes, and -- correctly -- no retirement. * * The second admin request then succeeded, because Elementor's migration had run during the * first. Waiting for that is the entire fix: nothing about the capability or nonce checks is * relaxed, no failure is suppressed, and no retry is introduced. V4 simply stops running * before the dependency it needs. * * 15 runs after that updater (10); a callback at 20 or later can rely on the design system being * installed already. */ public function register(): void { add_action( 'admin_init', [ $this, 'maybe_install' ], 15 ); add_action( 'admin_notices', [ $this, 'render_retry_notice' ] ); add_action( 'admin_post_' . self::RETRY_ACTION, [ $this, 'handle_retry_now' ] ); } /** * The delays between automatic attempts after a failed defaults import: 1 minute, 5 minutes, 30 minutes, 2 hours, * then 24 hours, which is also the maximum. */ public const RETRY_DELAYS = [ 60, 300, 1800, 7200, 86400 ]; /** The admin-post action behind the notice's "Retry Now" button. */ public const RETRY_ACTION = 'v4studio_retry_defaults_import'; public function maybe_install(): void { $this->install( false ); } /** * Install the shipped defaults into Elementor, or finish an install that did not complete. * * @param bool $force True for the administrator's "Retry Now": the back-off and the AJAX rule do not apply, the source lock still does. */ private function install( bool $force ): void { if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) { return; } $settings = Plugin::get_settings(); $installed_version = (string) ( $settings['defaults_version'] ?? '' ); $imported_version = (string) ( $settings['defaults_imported'] ?? '' ); if ( self::VERSION === $installed_version && self::VERSION === $imported_version ) { return; } $has_saved_design_system = '' !== trim( (string) ( $settings['variables_css'] ?? '' ) ) || '' !== trim( (string) ( $settings['classes_css'] ?? '' ) ); // Existing installs are adopted as-is. Defaults are only for genuinely fresh data. if ( self::VERSION !== $installed_version && $has_saved_design_system ) { $settings['defaults_version'] = self::VERSION; $settings['defaults_imported'] = self::VERSION; $settings['defaults_retry'] = []; Plugin::update_settings( $settings ); return; } /* * Elementor's atomic editor (V4) is off: its class and variable stores are not registered, so an attempt could * only fail (its REST routes answer "No route was found") and count towards the back-off. Nothing is attempted, * nothing is seeded and any back-off is cleared, so the first admin page after it is turned on installs at once. * render_retry_notice() says what to do instead of reporting a failure. */ if ( false === $this->service->atomic_editor_active() ) { if ( ! empty( $settings['defaults_retry'] ) ) { $settings['defaults_retry'] = []; Plugin::update_settings( $settings ); } return; } /* * A failed attempt is not repeated on every request. The retry state says how many attempts have failed and when * the next one may run. A heartbeat or any other AJAX request never starts a retry; it would only repeat the work * (and the Elementor cache clear that follows an import) for every open tab. The first attempt after a seed is not a * retry and is not held back. */ $retry = $this->retry_state( $settings ); if ( ! $force && $retry['attempts'] > 0 && ( ( function_exists( 'wp_doing_ajax' ) && wp_doing_ajax() ) || time() < $retry['next_attempt'] ) ) { return; } $defaults = $this->load_defaults(); if ( null === $defaults ) { return; } if ( self::VERSION !== $installed_version ) { $settings['variables_css'] = $defaults['variables_css']; $settings['classes_css'] = $defaults['classes_css']; $settings['last_variables'] = $defaults['variables']; $settings['last_classes'] = $defaults['classes']; $settings['fallback_payload']['variables'] = $defaults['variables']['items']; $settings['fallback_payload']['classes'] = $defaults['classes']['items']; $settings['aliases_initialized'] = true; $settings['alias_overrides'] = $this->alias_overrides( $defaults['variables']['items'] ); $settings['defaults_version'] = self::VERSION; $settings['defaults_imported'] = ''; $settings['defaults_retry'] = []; $settings = $this->seed_brand_data( $settings ); } $status = $this->service->get_status(); if ( empty( $status['elementor_active'] ) || empty( $status['variables_rest_api'] ) || empty( $status['global_classes_rest_api'] ) || empty( $status['global_repository'] ) ) { Plugin::update_settings( $settings ); return; } // After a reinstall, the values Elementor holds for V4 Studio's own variables are the ones to install and check. $adopted = $this->adopt_owned_values( $settings, $defaults['variables']['items'] ); $saved = []; // Otherwise the values saved for this site are: a token edited on the Tokens screen before the install was confirmed. $variable_items = [] === $adopted ? $this->saved_variable_items( $settings, $defaults['variables']['items'], $saved ) : (array) $settings['last_variables']['items']; $accepted = $this->agreed_customisations( $settings, $defaults['variables']['items'] ); $variable_import = $this->service->import_variables_verified( $variable_items, false, null, null, $accepted ); if ( [] !== $adopted ) { $variable_import['adopted'] = array_keys( $adopted ); } if ( [] !== $saved ) { $variable_import['saved'] = $saved; } // Verified: a defaults install that Elementor accepted but did not store must not be // reported as a successful seed. $class_import = $this->service->import_classes_verified( $defaults['classes']['items'], false ); $settings['last_import']['variables'] = $variable_import; $settings['last_import']['classes'] = $class_import; $succeeded = $this->import_succeeded( $variable_import ) && $this->import_succeeded( $class_import ); $wrote = ! empty( $variable_import['imported'] ) || ! empty( $class_import['imported'] ); if ( $succeeded ) { $settings['defaults_imported'] = self::VERSION; $settings['defaults_retry'] = []; /* * PERSIST FIRST, THEN REPAIR. The repair reads the authored variable values through * the service, which reads them from SAVED settings -- not from this local array. Run * against unsaved settings it finds no authored token for any font variable and * reports "the bound font variable has no authored token; left unchanged" for all * four, writing nothing. That was measured, not guessed. * * So the seeded CSS is written before the repair reads it. The final * Plugin::update_settings() below then persists the manifest and report this returns. * One extra option write, on a fresh install only. */ Plugin::update_settings( $settings ); $settings = $this->repair_seeded_font_stacks( $settings ); $wrote = $wrote || (int) ( $settings['font_stack_report']['written'] ?? 0 ) > 0 || (int) ( $settings['font_stack_report']['removed'] ?? 0 ) > 0; /* * fallback_payload IS DELIBERATELY LEFT POPULATED HERE. It used to be reset to two * empty arrays at this point, on the reasonable-sounding grounds that Elementor now * holds the design system so no recovery content is needed. That was wrong twice * over, and it made the fresh-install stamp below unreachable. * * First, the payload is what the VERIFIER compares against: * verify_design_system_in_elementor() builds its expected label set from * fallback_payload['classes']. Emptied, the expected set is empty, the comparison * loop never runs, classes_verified lands on 0 with no problems reported, and the * "nothing was actually verified" guard turns the stamp into ok=false. So the * fresh-install stamp added below could never succeed, and retirement never engaged * on ANY clean install -- the fallback stylesheet stayed active permanently, which * is precisely the failure that stamp was added to fix. * * Second, the payload is the recovery stylesheet's CONTENT. Emptying it does not * mean "the fallback is off" -- the GATE decides that. It means that if verification * ever fails afterwards, the fallback switches on with nothing to serve, so the * safety net silently holds no CSS at the one moment it is needed. * * Every other write path leaves it populated: save_css() sets * fallback_payload[$kind] = $parsed['items'] on every save, import and reset. A * fresh install now matches, using the items the seed just wrote above. */ } else { // Kept visible and retryable: what failed, how often, and when the next automatic attempt is due. Nothing is marked done. $settings['defaults_retry'] = $this->next_retry_state( $retry, $variable_import, $class_import ); } Plugin::update_settings( $settings ); // Elementor's generated CSS is cleared when the import or the repair actually changed something, not on every attempt. if ( $wrote ) { $this->service->clear_elementor_cache(); } /* * A fresh install is the FIRST convergence, and until now it was also a missing one. * The stamp was never written by any production path, so a new site had nothing for the * gate to read and the fallback stylesheet stayed active permanently — the retirement * this whole area exists to perform never happened on any site but a hand-stamped one. * * Only a seed that actually landed is stamped. A failed or partial import leaves the * gate unstamped, which keeps the fallback serving, which is the safe direction. */ if ( $succeeded ) { $this->service->verify_and_stamp_fallback_retirement(); } } /** * The default values this site has deliberately customised, where V4's own records and Elementor agree. * * A value counts only when ALL of these hold: it is a generated alias; V4 recorded an override for it; the stored * source declares exactly that value; and it differs from the shipped one. The verifier then also requires Elementor * to hold the same value. A value that only appears in one of the places, or that nothing recorded, is not accepted: * that is drift, and it stays a failure. * * @param array $settings * @param array> $variables The shipped default items. * @return array label => value */ private function agreed_customisations( array $settings, array $variables ): array { $overrides = is_array( $settings['alias_overrides'] ?? null ) ? $settings['alias_overrides'] : []; $source = (string) ( $settings['variables_css'] ?? '' ); $accepted = []; foreach ( $variables as $variable ) { $name = (string) ( $variable['name'] ?? '' ); $label = sanitize_key( (string) ( $variable['label'] ?? '' ) ); if ( '' === $label || ! in_array( $name, self::ALIAS_NAMES, true ) || ! isset( $overrides[ $name ] ) ) { continue; } $recorded = trim( (string) $overrides[ $name ] ); $shipped = trim( (string) ( $variable['value'] ?? '' ) ); if ( '' === $recorded || $recorded === $shipped ) { continue; } if ( $this->declared_value( $source, $name ) === $recorded ) { $accepted[ $label ] = $recorded; } } return $accepted; } /** * The values Elementor holds for variables V4 Studio created, taken into the settings being installed. * * Uninstalling removes `v4studio_settings` and keeps the ownership ledger and Elementor's variables, with any value * the user changed. When V4 Studio is installed again, those values are the site's design system, so the install * uses them instead of the shipped ones: the Tokens screen shows them, the backup stylesheet matches them and the * verified import accepts them. * * A value is taken only when all of these hold: the label is a shipped one; the ledger's active id for it is the id * Elementor lists for it; Elementor's value is not empty, has the type the shipped variable is written as, and is a * value the Tokens screen accepts for that type; the stored source still declares the shipped value (a value saved * on the Tokens screen is never replaced); and Elementor's value differs from the shipped one. Any other difference * is left to the verified import, which still reports it. * * A font added on the Tokens screen (`--font-custom-*`) is taken back the same way, so the screen lists it again: * the ledger holds the label active under the id Elementor lists, Elementor stores it as a font variable, the * stored source does not declare it yet, and its family passes the font check. Elementor holds the family alone, * so it is declared with the generic fallback Elementor's value names, or sans-serif. * * @param array $settings The settings being installed; updated when a value is taken. * @param array> $variables The shipped default items. * @return array label => the value taken */ private function adopt_owned_values( array &$settings, array $variables ): array { $ledger = Variable_Ownership_Ledger::load(); if ( [] === $ledger->active_labels() ) { return []; } $listed = $this->service->listed_variables_by_label(); if ( empty( $listed ) ) { return []; } $css = (string) ( $settings['variables_css'] ?? '' ); $adopted = []; $aliases = []; foreach ( $variables as $variable ) { $name = (string) ( $variable['name'] ?? '' ); $label = sanitize_key( (string) ( $variable['label'] ?? '' ) ); $shipped = trim( (string) ( $variable['value'] ?? '' ) ); $entry = $listed[ $label ] ?? null; if ( '' === $label || '' === $name || ! is_array( $entry ) || ! empty( $entry['deleted'] ) ) { continue; } $owned_id = $ledger->active_id( $label ); if ( '' === $owned_id || (string) ( $entry['id'] ?? '' ) !== $owned_id ) { continue; } $item = is_array( $entry['item'] ?? null ) ? $entry['item'] : []; $value = is_string( $item['value'] ?? null ) ? trim( $item['value'] ) : ''; $type = $this->service->variable_type_for( (string) ( $variable['type'] ?? '' ), $shipped ); if ( '' === $value || $value === $shipped || null === $type || (string) ( $item['type'] ?? '' ) !== $type ) { continue; } if ( $this->declared_value( $css, $name ) !== $shipped ) { continue; } $value = $this->accepted_value( $type, $value, $shipped ); if ( null === $value || $value === $shipped ) { continue; } $candidate = $this->with_declaration( $css, $name, $value ); if ( null === $candidate || $this->declared_value( $candidate, $name ) !== $value ) { continue; } $css = $candidate; $adopted[ $label ] = $value; if ( in_array( $name, self::ALIAS_NAMES, true ) ) { $aliases[ $name ] = $value; } } $fonts = 0; foreach ( $ledger->active_labels() as $label ) { $label = (string) $label; $name = '--' . $label; $entry = $listed[ $label ] ?? null; if ( ! $this->is_added_font_name( $name ) || ! is_array( $entry ) || ! empty( $entry['deleted'] ) || (string) ( $entry['id'] ?? '' ) !== $ledger->active_id( $label ) ) { continue; } $item = is_array( $entry['item'] ?? null ) ? $entry['item'] : []; $value = 'global-font-variable' === (string) ( $item['type'] ?? '' ) && is_string( $item['value'] ?? null ) ? $this->added_font_value( $item['value'] ) : null; if ( null === $value || '' !== $this->declared_value( $css, $name ) ) { continue; } $candidate = $this->with_added_declaration( $css, $name, $value ); if ( null === $candidate || $this->declared_value( $candidate, $name ) !== $value ) { continue; } $css = $candidate; $adopted[ $label ] = $value; ++$fonts; } if ( [] === $adopted ) { return []; } $parsed = $this->parser->parse_variables( $css ); // The rewritten source must parse as completely as the shipped one did, plus any font taken back; if it does not, nothing is taken. if ( self::EXPECTED_VARIABLES + $fonts !== count( $parsed['items'] ?? [] ) || ! empty( $parsed['skipped'] ) || ! empty( $parsed['errors'] ) ) { return []; } $settings['variables_css'] = $css; $settings['last_variables'] = $parsed; $settings['fallback_payload']['variables'] = $parsed['items']; $settings['alias_overrides'] = array_merge( (array) ( $settings['alias_overrides'] ?? [] ), $aliases ); return $adopted; } /** * The shipped items to install and check, each carrying the value saved for this site where that value can be trusted. * * A token saved on the Tokens screen while the first install was still unconfirmed is written to Elementor and to the * stored source. A later attempt ("Retry Now" or the automatic one) checks that saved value instead of the shipped one, * so it finishes and keeps the edit. The saved value is used only when all of these hold: the label is a shipped one; the * stored source declares a value for it that differs from the shipped one; the ownership ledger holds the label active * under the id Elementor lists; Elementor stores it with the type the shipped variable is written as; and the saved * value passes the Tokens screen's check for that type. Otherwise the shipped value stays the one checked. Either way * the verified import then requires Elementor to hold the value, so a value Elementor does not hold is still a failure. * * @param array $settings The settings being installed. * @param array> $variables The shipped default items. * @param string[] $saved Set to the labels whose saved value is used. * @return array> */ private function saved_variable_items( array $settings, array $variables, array &$saved ): array { $css = (string) ( $settings['variables_css'] ?? '' ); if ( '' === $css ) { return $variables; } $ledger = null; $listed = null; foreach ( $variables as $index => $variable ) { $name = (string) ( $variable['name'] ?? '' ); $label = sanitize_key( (string) ( $variable['label'] ?? '' ) ); $shipped = trim( (string) ( $variable['value'] ?? '' ) ); $value = '' === $name ? '' : $this->declared_value( $css, $name ); if ( '' === $label || '' === $value || $value === $shipped ) { continue; } $ledger = $ledger ?? Variable_Ownership_Ledger::load(); $listed = $listed ?? (array) $this->service->listed_variables_by_label(); $entry = $listed[ $label ] ?? null; $owned = $ledger->active_id( $label ); if ( ! is_array( $entry ) || ! empty( $entry['deleted'] ) || '' === $owned || (string) ( $entry['id'] ?? '' ) !== $owned ) { continue; } $type = $this->service->variable_type_for( (string) ( $variable['type'] ?? '' ), $shipped ); $item = is_array( $entry['item'] ?? null ) ? $entry['item'] : []; if ( null === $type || (string) ( $item['type'] ?? '' ) !== $type || ! $this->saved_value_passes( $type, $value ) ) { continue; } $variables[ $index ]['value'] = $value; $saved[] = $label; } return $variables; } /** Does a value saved for this site pass the Tokens screen's check for this variable type? */ private function saved_value_passes( string $type, string $value ): bool { if ( preg_match( '/^var\(\s*--[a-zA-Z_][a-zA-Z0-9_-]*\s*\)$/', $value ) ) { return 'global-font-variable' !== $type; } switch ( $type ) { case 'global-color-variable': return null !== Design_Token_Value::color( $value ); case 'global-custom-size-variable': return null !== Design_Token_Value::size( $value ) || null !== Design_Token_Value::number( $value ); case 'global-font-variable': $model = Design_Token_Value::describe( $value ); return 'font' === ( $model['kind'] ?? '' ) && null !== Design_Token_Value::font( (string) $model['family'], (string) $model['generic'] ); } return false; } /** * Elementor's value in the form the Tokens screen accepts for this variable type, or null when it accepts none. * Elementor holds a font variable's family alone; it is taken with the generic fallback of the shipped stack. */ private function accepted_value( string $type, string $value, string $shipped ): ?string { if ( preg_match( '/^var\(\s*--[a-zA-Z_][a-zA-Z0-9_-]*\s*\)$/', $value ) ) { return 'global-font-variable' === $type ? null : $value; } switch ( $type ) { case 'global-color-variable': return Design_Token_Value::color( $value ); case 'global-custom-size-variable': return Design_Token_Value::size( $value ) ?? Design_Token_Value::number( $value ); case 'global-font-variable': $shipped_model = Design_Token_Value::describe( $shipped ); $model = Design_Token_Value::describe( $value ); $family = 'font' === ( $model['kind'] ?? '' ) ? (string) $model['family'] : trim( $value, " \t\"'" ); if ( 0 === strcasecmp( $family, (string) ( $shipped_model['family'] ?? '' ) ) ) { return null; // The same family: Elementor's shorter form is the same token. } return Design_Token_Value::font( $family, (string) ( $shipped_model['generic'] ?? 'sans-serif' ) ); } return null; } /** Is this the name of a font added on the Tokens screen (Variable_Form::is_added_font_name())? */ private function is_added_font_name( string $name ): bool { return strlen( $name ) <= 64 && 1 === preg_match( '/^--font-custom-[a-z0-9]+(?:-[a-z0-9]+)*$/', $name ); } /** An added font's value from Elementor's: its family with the generic fallback it names, or sans-serif; null when the family does not pass. */ private function added_font_value( string $value ): ?string { $model = Design_Token_Value::describe( trim( $value ) ); if ( 'font' === ( $model['kind'] ?? '' ) ) { return Design_Token_Value::font( (string) $model['family'], (string) $model['generic'] ); } return Design_Token_Value::font( trim( $value, " \t\"'" ), 'sans-serif' ); } /** The stylesheet with `$name: $value;` added at the end of its block, or null when it has no block. */ private function with_added_declaration( string $css, string $name, string $value ): ?string { $position = strrpos( $css, '}' ); if ( false === $position ) { return null; } return rtrim( substr( $css, 0, $position ) ) . "\n" . $name . ': ' . $value . ";\n" . substr( $css, $position ); } /** The stylesheet with every declaration of `$name` set to `$value`, or null when it declares none. */ private function with_declaration( string $css, string $name, string $value ): ?string { $count = 0; $next = preg_replace_callback( '/((?:^|[;{\s])' . preg_quote( $name, '/' ) . '\s*:\s*)([^;}]+)/', static fn( array $m ): string => $m[1] . $value, $css, -1, $count ); return null === $next || 0 === $count ? null : $next; } /** The last value a stylesheet declares for a custom property, or '' when it declares none. */ private function declared_value( string $css, string $name ): string { if ( ! preg_match_all( '/(?:^|[;{\s])' . preg_quote( $name, '/' ) . '\s*:\s*([^;}]+)/', $css, $matches ) ) { return ''; } return trim( (string) end( $matches[1] ) ); } /** * @param array $settings * @return array{attempts:int,failed_at:int,next_attempt:int,step:string,reasons:array,preserved:int,version:string} */ public function retry_state( array $settings ): array { $raw = is_array( $settings['defaults_retry'] ?? null ) ? $settings['defaults_retry'] : []; if ( self::VERSION !== (string) ( $raw['version'] ?? '' ) ) { $raw = []; } return [ 'attempts' => max( 0, (int) ( $raw['attempts'] ?? 0 ) ), 'failed_at' => (int) ( $raw['failed_at'] ?? 0 ), 'next_attempt' => (int) ( $raw['next_attempt'] ?? 0 ), 'step' => (string) ( $raw['step'] ?? '' ), 'reasons' => array_values( array_map( 'strval', (array) ( $raw['reasons'] ?? [] ) ) ), 'preserved' => (int) ( $raw['preserved'] ?? 0 ), 'version' => self::VERSION, ]; } /** * The state after one more failed attempt. * * @param array $previous * @return array{attempts:int,failed_at:int,next_attempt:int,step:string,reasons:array,preserved:int,version:string} */ private function next_retry_state( array $previous, array $variable_import, array $class_import ): array { $attempts = (int) $previous['attempts'] + 1; $delay = self::RETRY_DELAYS[ min( $attempts, count( self::RETRY_DELAYS ) ) - 1 ]; $step = $this->import_succeeded( $variable_import ) ? 'classes' : 'variables'; $failed = 'variables' === $step ? (array) ( $variable_import['failed'] ?? [] ) : (array) ( $class_import['failed'] ?? [] ); $reasons = []; foreach ( array_slice( $failed, 0, 5 ) as $entry ) { $reasons[] = is_array( $entry ) ? (string) ( $entry['reason'] ?? $entry['item'] ?? '' ) : (string) $entry; } if ( empty( $failed ) && ! empty( $variable_import['fallback'] ) ) { $reasons[] = __( 'Elementor was not ready to accept the defaults.', 'v4studio' ); } return [ 'attempts' => $attempts, 'failed_at' => time(), 'next_attempt' => time() + $delay, 'step' => $step, 'reasons' => array_values( array_filter( $reasons, 'strlen' ) ), 'preserved' => $this->kept_customisations( $variable_import ), 'version' => self::VERSION, ]; } /** * How many customised values the attempt kept, for the notice: the ones the verified import set apart as preserved, and * the values saved for this site or taken back from Elementor (`saved`, `adopted`) that did not fail. A failure is matched * by its `label` key, never by its message: the messages are translated and worded differently. */ private function kept_customisations( array $variable_import ): int { $failed = array_map( 'strval', array_column( array_filter( (array) ( $variable_import['failed'] ?? [] ), 'is_array' ), 'label' ) ); $kept = array_map( 'strval', array_merge( (array) ( $variable_import['saved'] ?? [] ), (array) ( $variable_import['adopted'] ?? [] ) ) ); $labels = array_map( 'strval', array_column( (array) ( $variable_import['preserved'] ?? [] ), 'label' ) ); return count( array_unique( array_merge( $labels, array_diff( $kept, $failed ) ) ) ); } /** * An administrator-only notice after the first failed attempt, until an attempt succeeds. While Elementor's atomic * editor is off it is replaced, on V4 Studio's screen, by what to turn on and where: there is no failure to report. */ public function render_retry_notice(): void { if ( ! current_user_can( 'manage_options' ) ) { return; } // V4 Studio's screen only (WordPress.org guideline 11), the failure notice as much as the activation notice. if ( ! $this->on_v4studio_screen() ) { return; } if ( false === $this->service->atomic_editor_active() ) { $this->render_atomic_editor_notice(); return; } $settings = Plugin::get_settings(); if ( self::VERSION === (string) ( $settings['defaults_imported'] ?? '' ) ) { return; } $retry = $this->retry_state( $settings ); if ( $retry['attempts'] < 1 ) { return; } $step = 'classes' === $retry['step'] ? __( 'classes', 'v4studio' ) : __( 'variables', 'v4studio' ); $when = $retry['next_attempt'] > time() ? sprintf( /* translators: 1: time of day, 2: how long from now, such as "5 mins". */ __( 'V4 Studio will try again automatically at %1$s (in %2$s).', 'v4studio' ), wp_date( (string) get_option( 'time_format' ), $retry['next_attempt'] ), human_time_diff( time(), $retry['next_attempt'] ) ) : __( 'A retry is due now; it runs on the next admin page load, or you can retry now.', 'v4studio' ); $kept = $retry['preserved'] > 0 ? sprintf( /* translators: %d: number of customized values. */ _n( '%d value you customized was kept as it is.', '%d values you customized were kept as they are.', $retry['preserved'], 'v4studio' ), $retry['preserved'] ) : ''; $outcome = $this->retry_outcome(); echo '

' . esc_html__( 'V4 Studio could not finish installing its default design system.', 'v4studio' ) . ' '; /* translators: %s: the step that was not confirmed, "variables" or "classes". */ echo esc_html( sprintf( __( 'The %s step was not confirmed.', 'v4studio' ), $step ) ); echo ' ' . esc_html__( 'Your existing design system and settings were not changed.', 'v4studio' ) . ' ' . esc_html( $kept ) . ' ' . esc_html( $when ) . '

'; if ( ! empty( $retry['reasons'] ) ) { echo '

' . esc_html( (string) $retry['reasons'][0] ) . '

'; } if ( '' !== $outcome ) { echo '

' . esc_html( $outcome ) . '

'; } echo '
'; wp_nonce_field( self::RETRY_ACTION ); echo '

'; } private function on_v4studio_screen(): bool { $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; // V4 Studio's page, where its notices show (the Atomic Editor notice, the defaults retry notice): its // top-level screen, or its page query value under any menu. if ( $screen && 'toplevel_page_v4studio' === $screen->id ) { return true; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- WordPress admin page routing uses the sanitized page query arg. $page = isset( $_GET['page'] ) && is_string( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; return is_admin() && 'v4studio' === $page; } /** Elementor's atomic editor is off, so turn it on, with a link. */ private function render_atomic_editor_notice(): void { $installed = self::VERSION === (string) ( Plugin::get_settings()['defaults_imported'] ?? '' ); echo '

' . esc_html__( 'V4 Studio needs Elementor\'s Atomic Editor (Editor V4).', 'v4studio' ) . ' '; echo esc_html( $installed ? __( 'It is turned off, so Elementor does not load the classes and variables V4 Studio works with. Turn it on in Elementor\'s settings.', 'v4studio' ) : __( 'Turn it on in Elementor\'s settings, and V4 Studio installs its design system on your next admin page. Nothing has been changed yet.', 'v4studio' ) ); echo '

' . esc_html__( 'Turn On the Atomic Editor', 'v4studio' ) . '

'; } /** What the last "Retry Now" did, when this page was reached from it. */ private function retry_outcome(): string { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display only: a status word from our own redirect, shown as plain text. $flag = isset( $_GET['v4studio_defaults_retry'] ) && is_string( $_GET['v4studio_defaults_retry'] ) ? sanitize_key( wp_unslash( $_GET['v4studio_defaults_retry'] ) ) : ''; switch ( $flag ) { case 'busy': return __( 'Another change to the design system is being applied right now, so nothing was attempted. Try again in a moment.', 'v4studio' ); case 'failed': return __( 'The retry did not complete; the details above are from that attempt.', 'v4studio' ); default: return ''; } } /** * "Retry Now": nonce- and capability-protected, and it takes the Design Tokens save lock rather than racing a save. * The outcome is a status word on the redirect back, shown by render_retry_notice(). */ public function handle_retry_now(): void { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You are not allowed to do that.', 'v4studio' ), '', [ 'response' => 403 ] ); } check_admin_referer( self::RETRY_ACTION ); wp_safe_redirect( add_query_arg( 'v4studio_defaults_retry', $this->retry_now(), wp_get_referer() ?: admin_url() ) ); exit; } /** * One immediate attempt, outside the back-off, under the Design Tokens save lock, so it cannot overlap a save. * The lock is released when the attempt ends, and when the request ends, so a fatal error or a time-out * does not leave it held. * * @return string 'busy' (a Design Tokens save holds the lock; nothing was attempted), 'failed' or 'done'. */ public function retry_now(): string { if ( ! Tokens_Screen::acquire_save_lock() ) { return 'busy'; } register_shutdown_function( [ Tokens_Screen::class, 'release_save_lock' ] ); try { $this->install( true ); } finally { Tokens_Screen::release_save_lock(); } $settings = Plugin::get_settings(); return self::VERSION === (string) ( $settings['defaults_imported'] ?? '' ) ? 'done' : 'failed'; } /** * Give the seeded classes their authored font fallbacks, at seed time. * * WHY THIS IS HERE AND NOT ONLY IN save_css(). * * Elementor's `global-font-variable` holds ONE family by design, so an authored * `--font-body: "Inter", sans-serif` is stored as `Inter` and a class bound to it renders * `font-family: var(--font-body)` with no generic behind it. Font_Stack_Repair exists to put * the remaining families back, as a `custom_css` declaration in the same variant. * * It ran only from save_css(). A fresh install performs no save, so every new site carried * the four semantic font utilities WITHOUT their fallbacks until somebody happened to save or * reset -- and if the primary webfont failed to load, the browser fell back to its own * default instead of the authored generic. The repair was missing from precisely the * installs it was written for. Measured on a clean 4.3.0 lane: `custom_css` was null on all * four, and became the correct declaration after any save. * * NO DUPLICATED FONT-STACK LOGIC. This calls the same canonical service entry point * save_css() uses, so tail computation, ownership, tombstones, adopt-vs-write and * verification all behave identically. The only difference is when it runs. * * NO UNRELATED SAVE SIDE EFFECTS. save_css() also reparses CSS, rewrites fallback_payload, * re-imports, clears caches and restamps. None of that is wanted here -- the seed above just * did it. This takes the repair alone. * * IDEMPOTENT. It runs inside the once-per-version seed branch, so a second admin visit does * not reach it. Were it reached anyway, the manifest it reads and returns is what makes the * repair idempotent in save_css() too: an already-correct declaration is ADOPTED, not * rewritten, and no Elementor write is sent. * * USER VALUES ARE NOT TOUCHED. plan() leaves a variant whose font-family it does not own * alone and records it as a conflict; tombstone_user_deletions() makes a removal stick. * Those paths are unchanged and are the reason this can run unattended. * * BEFORE THE STAMP, deliberately. The caller stamps retirement after this returns, and the * stamp attests Elementor's state. Repairing afterwards would mutate the very state that was * just attested and leave the stamp describing something that no longer exists. * * Failure is reported, never thrown: a site that cannot be repaired still gets its seed. * * @param array $settings * @return array */ private function repair_seeded_font_stacks( array $settings ): array { $manifest = is_array( $settings[ Font_Stack_Repair::MANIFEST_KEY ] ?? null ) ? $settings[ Font_Stack_Repair::MANIFEST_KEY ] : []; try { $result = $this->service->repair_font_stacks( $manifest ); } catch ( \Throwable $error ) { return $settings; } $settings[ Font_Stack_Repair::MANIFEST_KEY ] = $result['manifest']; // Same shape save_css() records, so one reader serves both paths. $settings['font_stack_report'] = [ 'written' => (int) $result['written'], 'removed' => (int) $result['removed'], 'tombstoned' => array_values( $result['tombstoned'] ), 'unverified' => array_values( $result['unverified'] ), 'conflicts' => array_values( $result['conflicts'] ), 'diagnostics' => array_values( $result['diagnostics'] ), 'failed' => array_values( $result['failed'] ), ]; return $settings; } /** * Give a new installation its Brand Data, so the dynamic tags have something to return. * * Brand Data used to start completely empty, which meant every component built on the * Brand Data dynamic tags rendered blank on a new site until somebody opened the panel and * pressed Save. The seed is real stored values, not placeholder attributes, so the tags, the * admin form, export and the frontend all see the same thing. * * ONLY WHEN THERE IS NOTHING TO LOSE. It writes only if every value field is empty. A field * the user has filled in -- or deliberately emptied after the seed, since the marker below * stops the seed running twice -- is never touched. Labels are ignored when judging * emptiness: they always carry a catalogue default, so counting them would make an untouched * record look occupied. * * IDEMPOTENT TWICE OVER: the marker records that the seed has run, and the emptiness check * would refuse a second write anyway. Repeat admin visits do not reach this at all, because * the caller returns early once the defaults version is installed. * * The logos are attachments, created once and then found by their marker rather than created * again -- see Brand_Data_Logos. * * @param array $settings * @return array */ private function seed_brand_data( array $settings ): array { if ( ! class_exists( '\\V4STUDIO\\Brand_Data' ) ) { return $settings; } if ( ! empty( $settings['dynamic_data_seeded'] ) ) { return $settings; } $stored = is_array( $settings[ Brand_Data::SETTINGS_KEY ] ?? null ) ? $settings[ Brand_Data::SETTINGS_KEY ] : []; foreach ( Brand_Data::seed_values() as $key => $_value ) { if ( '' !== trim( (string) ( $stored[ $key ] ?? '' ) ) ) { return $settings; } } foreach ( Brand_Data::media_keys() as $key ) { if ( (int) ( $stored[ $key ] ?? 0 ) > 0 ) { return $settings; } } try { $record = Brand_Data::seed_record(); } catch ( \Throwable $error ) { return $settings; } /* * Labels the user already renamed are kept: the seed supplies values, and a label is the * user's word for a field, not part of the demo content. */ foreach ( Brand_Data::label_keys() as $key ) { $label_key = $key . '_label'; if ( '' !== trim( (string) ( $stored[ $label_key ] ?? '' ) ) ) { $record[ $label_key ] = $stored[ $label_key ]; } } $settings[ Brand_Data::SETTINGS_KEY ] = $record; $settings['dynamic_data_seeded'] = true; return $settings; } private function load_defaults(): ?array { $variables_css = $this->read_default_file( 'variables.css' ); $classes_css = $this->read_default_file( 'classes.css' ); if ( '' === $variables_css || '' === $classes_css ) { return null; } $variables = $this->parser->parse_variables( $variables_css ); $classes = $this->parser->parse_classes( $classes_css ); if ( self::EXPECTED_VARIABLES !== count( $variables['items'] ?? [] ) || self::EXPECTED_CLASS_VARIANTS !== count( $classes['items'] ?? [] ) || ! empty( $variables['skipped'] ) || ! empty( $classes['skipped'] ) || ! empty( $variables['errors'] ) || ! empty( $classes['errors'] ) ) { return null; } return [ 'variables_css' => $variables_css, 'classes_css' => $classes_css, 'variables' => $variables, 'classes' => $classes, ]; } private function read_default_file( string $filename ): string { $path = V4STUDIO_DIR . 'defaults/' . $filename; if ( ! is_readable( $path ) ) { return ''; } $contents = file_get_contents( $path ); return is_string( $contents ) ? trim( $contents ) . "\n" : ''; } private function alias_overrides( array $variables ): array { $values = []; foreach ( $variables as $variable ) { $name = (string) ( $variable['name'] ?? '' ); if ( in_array( $name, self::ALIAS_NAMES, true ) ) { $values[ $name ] = (string) ( $variable['value'] ?? '' ); } } return $values; } private function import_succeeded( array $result ): bool { return empty( $result['fallback'] ) && empty( $result['failed'] ); } }