['vs_ai_assistant_status', 'vs_client_secret', 'vs_encryption_key', 'vs_event_delivery_cursor', 'vs_event_delivery_generation', 'vs_event_delivery_lock', 'vs_event_delivery_status', 'vs_event_index_backfill_state', 'vs_event_last_cron_run', 'vs_event_storage_schema_version', 'vs_event_tracking_configuration_last_known', 'vs_installed', 'vs_refresh_token', 'vs_state_schema_version', 'vs_sync_reconciliation_last_completed', 'vs_sync_reconciliation_last_started', 'vs_tenant_id', 'vs_token_last_refresh', 'vs_token_refresh_failures', 'vs_token_refresh_lock', 'vs_valuespace_availability', 'vs_valuespace_client_id', 'vs_valuespace_connected_time', 'vs_valuespace_denied', 'vs_valuespace_last_error', 'vs_valuespace_was_connected', 'vs_version', 'vs_wc_catalog_collection_progress', 'vs_wc_catalog_pending_mode', 'vs_wc_catalog_push_enabled', 'vs_wc_catalog_source_feed_step', 'vs_wc_catalog_storage_schema', 'vs_wc_catalog_sync_last_error', 'vs_wc_catalog_sync_status', 'vs_wc_sync_completed_time', 'vs_widget_disabled_post_types', 'vs_widget_position', 'vs_widget_theme', 'vs_woocommerce_connected_time', 'vs_woocommerce_denied', 'vs_woocommerce_last_error', 'vs_wordpress_connected_time', 'vs_wordpress_denied', 'vs_wordpress_last_error', 'vs_wp_indexation_triggered', 'vs_wp_ingestion_status', 'vs_wp_sync_completed_time'], 'transient' => ['vs_access_token', 'vs_activation_redirect', 'vs_admin_notice', 'vs_billing_summary_cache', 'vs_code_verifier', 'vs_connection_status', 'vs_event_tracking_configuration', 'vs_gateway_unreachable', 'vs_pkce_verifier', 'vs_refresh_token_expires_at', 'vs_required_scopes', 'vs_token_expires_at', 'vs_token_refresh_cooldown', 'vs_token_refresh_retry_after'], 'dynamic_option_prefix' => ['vs_dynamic_transient_key_', 'vs_event_abandon_lock_', 'vs_event_session_lock_', 'vs_sync_dispatching_', 'vs_sync_pending_', 'vs_sync_running_'], 'dynamic_transient_prefix' => ['vs_bootstrap_nonce_', 'vs_contact_rate_', 'vs_event_rate_', 'vs_notice_suppressed_', 'vs_session_', 'vs_valuespace_authorization_state_', 'vs_valuespace_bootstrap_callback_state_', 'vs_valuespace_registration_state_', 'vs_woocommerce_callback_state_', 'vs_wordpress_callback_state_'], 'wp_cron' => ['vs_deliver_events', 'vs_monitor_scheduled_tasks', 'vs_reconcile_sync_jobs', 'vs_retry_user_access_revocation', 'vs_run_sync_service', 'vs_wc_catalog_push_refresh'], ]; } /** Match only explicitly owned keys and dynamic namespaces. */ function vasp_prefix_migration_owned(string $vasp_key, string $vasp_type): bool { $vasp_inventory = vasp_prefix_migration_inventory(); if (in_array($vasp_key, $vasp_inventory[$vasp_type] ?? [], true)) { return true; } foreach ($vasp_inventory['dynamic_' . $vasp_type . '_prefix'] ?? [] as $vasp_prefix) { if (strpos($vasp_key, $vasp_prefix) === 0) { return true; } } return false; } /** Read raw option bytes; PHP must never deserialize and reserialize credentials. */ function vasp_prefix_migration_rows(): array { global $wpdb; $vasp_inventory = vasp_prefix_migration_inventory(); $vasp_conditions = []; $vasp_arguments = [$wpdb->options]; foreach ($vasp_inventory['option'] as $vasp_key) { $vasp_conditions[] = 'option_name = %s'; $vasp_arguments[] = $vasp_key; } foreach ($vasp_inventory['dynamic_option_prefix'] as $vasp_prefix) { $vasp_conditions[] = 'option_name LIKE %s'; $vasp_arguments[] = $wpdb->esc_like($vasp_prefix) . '%'; } foreach (['_transient_', '_transient_timeout_'] as $vasp_storage_prefix) { foreach ($vasp_inventory['transient'] as $vasp_key) { $vasp_conditions[] = 'option_name = %s'; $vasp_arguments[] = $vasp_storage_prefix . $vasp_key; } foreach ($vasp_inventory['dynamic_transient_prefix'] as $vasp_prefix) { $vasp_conditions[] = 'option_name LIKE %s'; $vasp_arguments[] = $wpdb->esc_like($vasp_storage_prefix . $vasp_prefix) . '%'; } } // Conditions contain only fixed placeholder clauses; identifiers and values // are bound below. The scanner cannot infer the generated OR fragment. // phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared $vasp_rows = $wpdb->get_results($wpdb->prepare( 'SELECT option_id, option_name, option_value, autoload FROM %i' . ' WHERE ' . implode(' OR ', $vasp_conditions), $vasp_arguments ), ARRAY_A); // phpcs:enable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared if ($wpdb->last_error || !is_array($vasp_rows)) { throw new RuntimeException('option_read'); } // Recheck case-sensitively because MySQL's option-name collation may not be. return array_values(array_filter($vasp_rows, function ($vasp_row) { $vasp_name = (string) $vasp_row['option_name']; foreach (['_transient_timeout_', '_transient_'] as $vasp_prefix) { if (strpos($vasp_name, $vasp_prefix) === 0) { return vasp_prefix_migration_owned(substr($vasp_name, strlen($vasp_prefix)), 'transient'); } } if (strpos($vasp_name, 'vs_dynamic_transient_key_') === 0 && !vasp_prefix_migration_owned((string) $vasp_row['option_value'], 'transient')) { return false; // Retired transient registries stay with historical cleanup. } return vasp_prefix_migration_owned($vasp_name, 'option'); })); } /** Build exact name changes and the exceptional registry value/hash change. */ function vasp_prefix_migration_plan(array $vasp_rows): array { $vasp_plan = []; foreach ($vasp_rows as $vasp_row) { $vasp_old = (string) $vasp_row['option_name']; $vasp_new = preg_replace('/^(_transient_(?:timeout_)?)?vs_/', '$1vasp_', $vasp_old); $vasp_value = (string) $vasp_row['option_value']; if (strpos($vasp_old, 'vs_dynamic_transient_key_') === 0) { // Registry entries contain exact plain transient names, not serialized data. if (!vasp_prefix_migration_owned($vasp_value, 'transient') || $vasp_old !== 'vs_dynamic_transient_key_' . hash('sha256', $vasp_value)) { throw new RuntimeException('registry_invalid'); } $vasp_value = 'vasp_' . substr($vasp_value, 3); if (strlen($vasp_value) > 172) { throw new RuntimeException('transient_name_too_long'); } $vasp_new = 'vasp_dynamic_transient_key_' . hash('sha256', $vasp_value); } // WordPress removes strict SQL modes on some installations. Reject an // oversized name before MySQL can silently truncate a renamed row. if (strlen($vasp_new) > 191) { throw new RuntimeException('option_name_too_long'); } foreach (['_transient_timeout_', '_transient_'] as $vasp_storage_prefix) { if (strpos($vasp_new, $vasp_storage_prefix) === 0 && strlen(substr($vasp_new, strlen($vasp_storage_prefix))) > 172) { throw new RuntimeException('transient_name_too_long'); } } $vasp_plan[] = [$vasp_row, $vasp_new, $vasp_value]; } return $vasp_plan; } /** Preserve timestamps, argument hashes, arguments, interval and unrelated cron entries. */ function vasp_prefix_migration_cron(array $vasp_cron): array { $vasp_hooks = vasp_prefix_migration_inventory()['wp_cron']; foreach ($vasp_cron as $vasp_timestamp => $vasp_events) { if (!is_array($vasp_events)) { continue; } foreach ($vasp_hooks as $vasp_old_hook) { if (!isset($vasp_events[$vasp_old_hook])) { continue; } $vasp_new_hook = 'vasp_' . substr($vasp_old_hook, 3); $vasp_migrated = $vasp_events[$vasp_old_hook]; foreach ($vasp_migrated as &$vasp_event) { if (($vasp_event['schedule'] ?? '') === 'every_5_minutes') { $vasp_event['schedule'] = 'vasp_every_5_minutes'; } } unset($vasp_event); foreach ($vasp_migrated as $vasp_signature => $vasp_event) { if (isset($vasp_cron[$vasp_timestamp][$vasp_new_hook][$vasp_signature]) && $vasp_cron[$vasp_timestamp][$vasp_new_hook][$vasp_signature] !== $vasp_event) { throw new RuntimeException('cron_conflict'); } $vasp_cron[$vasp_timestamp][$vasp_new_hook][$vasp_signature] = $vasp_event; } unset($vasp_cron[$vasp_timestamp][$vasp_old_hook]); } } return $vasp_cron; } /** A failed query always stops bootstrap; never expose raw database errors. */ function vasp_prefix_migration_query(string $vasp_sql): int { global $wpdb; // Every caller supplies a prepare() result; no unprepared SQL is accepted. // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared $vasp_result = $wpdb->query($vasp_sql); if ($vasp_result === false) { throw new RuntimeException('write_failed'); } return (int) $vasp_result; } /** Detect durable work recreated by an old request after the success marker. */ function vasp_prefix_migration_late_state(): bool { global $wpdb; $vasp_tables = $wpdb->get_col($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($wpdb->prefix . 'vs_') . '%')); if ($wpdb->last_error || !is_array($vasp_tables)) { throw new RuntimeException('table_read'); } foreach (['catalog_hashes', 'catalog_queue', 'event_index', 'event_aggregate'] as $vasp_suffix) { if (in_array($wpdb->prefix . 'vs_' . $vasp_suffix, $vasp_tables, true)) { return true; } } $vasp_cron = get_option('cron', []); if (!is_array($vasp_cron)) { throw new RuntimeException('cron_invalid'); } foreach ($vasp_cron as $vasp_events) { if (!is_array($vasp_events)) { continue; } foreach (vasp_prefix_migration_inventory()['wp_cron'] as $vasp_hook) { if (isset($vasp_events[$vasp_hook])) { return true; } } } return false; } /** * Migrate before loading feature code, options, credentials or table consumers. * * GET_LOCK coordinates new PHP workers only. Every request checks owned legacy * options, and the bounded compatibility window also checks tables and cron. * Late old writers therefore cause another migration attempt; conflicting * destinations pause bootstrap while preserving both copies for review. * Cache-only transients remain under their old keys until their original TTL. * Exact-key fallback hooks retain in-flight OAuth state without TTL extension. */ function vasp_migrate_legacy_prefix(): bool { global $wpdb; $vasp_lock = 'vasp_prefix_' . substr(hash('sha256', $wpdb->options), 0, 40); $vasp_locked = false; $vasp_cache_keys = []; try { $vasp_compatibility = get_option('vasp_prefix_migration_transients', []); if (is_array($vasp_compatibility) && (int) ($vasp_compatibility['until'] ?? 0) >= time()) { vasp_prefix_migration_transient_fallbacks((array) ($vasp_compatibility['keys'] ?? [])); } $vasp_rows = vasp_prefix_migration_rows(); // The marker is per-site because it lives in this site's options table. // Inspect legacy rows even after success to detect a late old-code writer. if (!$vasp_rows && get_option('vasp_prefix_migration_version', '') === '1') { if ((int) ($vasp_compatibility['until'] ?? 0) < time() || !vasp_prefix_migration_late_state()) { return true; } } $vasp_locked = (string) $wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s, 1)', $vasp_lock)) === '1'; if (!$vasp_locked) { throw new RuntimeException('lock_unavailable'); } // Another worker may have completed migration while this request waited. wp_cache_delete('vasp_prefix_migration_transients', 'options'); $vasp_compatibility = get_option('vasp_prefix_migration_transients', []); $vasp_plan = vasp_prefix_migration_plan(vasp_prefix_migration_rows()); // Preflight all conflicts before changing a single option or table. foreach ($vasp_plan as [$vasp_row, $vasp_new]) { $vasp_exists = $wpdb->get_var($wpdb->prepare( 'SELECT option_id FROM %i WHERE option_name = %s', $wpdb->options, $vasp_new )); if ($wpdb->last_error || $vasp_exists !== null) { throw new RuntimeException('option_conflict'); } } $vasp_rename = []; $vasp_rename_args = []; // New suffixes are no longer than their old counterparts, including sites // whose custom WordPress table prefix already approaches MySQL's limit. foreach (['catalog_hashes' => 'cat_hashes', 'catalog_queue' => 'cat_queue', 'event_index' => 'evt_index', 'event_aggregate' => 'evt_aggregate'] as $vasp_suffix => $vasp_new_suffix) { $vasp_old = $wpdb->prefix . 'vs_' . $vasp_suffix; $vasp_new = $wpdb->prefix . 'vasp_' . $vasp_new_suffix; if (strlen($vasp_old) > 64 || strlen($vasp_new) > 64) { throw new RuntimeException('table_name_too_long'); } $vasp_found = []; foreach ([$vasp_old, $vasp_new] as $vasp_table) { $vasp_found[] = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($vasp_table))) === $vasp_table; if ($wpdb->last_error) { throw new RuntimeException('table_read'); } } if ($vasp_found[0] && $vasp_found[1]) { throw new RuntimeException('table_conflict'); } if ($vasp_found[0]) { $vasp_rename[] = '%i TO %i'; $vasp_rename_args[] = $vasp_old; $vasp_rename_args[] = $vasp_new; } } $vasp_cron_row = $wpdb->get_row($wpdb->prepare( "SELECT option_value FROM %i WHERE option_name = 'cron'", $wpdb->options ), ARRAY_A); if ($wpdb->last_error) { throw new RuntimeException('cron_read'); } $vasp_cron_old = $vasp_cron_row['option_value'] ?? null; $vasp_cron_new = $vasp_cron_old; if ($vasp_cron_old !== null) { $vasp_cron = maybe_unserialize($vasp_cron_old); if (!is_array($vasp_cron)) { throw new RuntimeException('cron_invalid'); } $vasp_cron_migrated = vasp_prefix_migration_cron($vasp_cron); if ($vasp_cron_migrated !== $vasp_cron) { $vasp_cron_new = serialize($vasp_cron_migrated); } } // Persist the exact cache-only key inventory before renaming its DB registry. // The fixed deadline is never extended by retries or normal requests. $vasp_transients = vasp_prefix_migration_inventory()['transient']; foreach ($vasp_plan as [$vasp_row]) { if (strpos($vasp_row['option_name'], 'vs_dynamic_transient_key_') === 0) { $vasp_transients[] = (string) $vasp_row['option_value']; } } if (wp_using_ext_object_cache()) { $vasp_transients = array_values(array_filter($vasp_transients, function ($vasp_key) { return get_transient($vasp_key) !== false; })); } $vasp_compatibility = is_array($vasp_compatibility) ? $vasp_compatibility : []; $vasp_compatibility = [ 'until' => $vasp_compatibility['until'] ?? time() + 30 * 86400, 'keys' => array_values(array_unique(array_merge((array) ($vasp_compatibility['keys'] ?? []), $vasp_transients))), ]; if (!update_option('vasp_prefix_migration_transients', $vasp_compatibility, false) && get_option('vasp_prefix_migration_transients', []) !== $vasp_compatibility) { throw new RuntimeException('transient_inventory_failed'); } if ((int) $vasp_compatibility['until'] >= time()) { vasp_prefix_migration_transient_fallbacks($vasp_compatibility['keys']); } if ($vasp_rename) { // Only fixed identifier-placeholder pairs from the four-table map // are joined here; all table names are bound in one atomic rename. // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Generated SQL contains only literal %i TO %i fragments. vasp_prefix_migration_query($wpdb->prepare('RENAME TABLE ' . implode(', ', $vasp_rename), $vasp_rename_args)); } foreach ($vasp_plan as [$vasp_row, $vasp_new, $vasp_value]) { $vasp_cache_keys[] = (string) $vasp_row['option_name']; $vasp_cache_keys[] = $vasp_new; // CAS prevents overwriting a legacy value changed after preflight. $vasp_updated = vasp_prefix_migration_query($wpdb->prepare( 'UPDATE %i SET option_name = %s, option_value = %s WHERE option_id = %d AND BINARY option_name = BINARY %s AND BINARY option_value = BINARY %s AND autoload = %s', $wpdb->options, $vasp_new, $vasp_value, $vasp_row['option_id'], $vasp_row['option_name'], $vasp_row['option_value'], $vasp_row['autoload'] )); if ($vasp_updated !== 1) { throw new RuntimeException('option_changed'); } } if ($vasp_cron_new !== $vasp_cron_old) { $vasp_cache_keys[] = 'cron'; if (vasp_prefix_migration_query($wpdb->prepare( "UPDATE %i SET option_value = %s WHERE option_name = 'cron' AND BINARY option_value = BINARY %s", $wpdb->options, $vasp_cron_new, $vasp_cron_old )) !== 1) { throw new RuntimeException('cron_changed'); } } if (vasp_prefix_migration_rows()) { throw new RuntimeException('legacy_writer_active'); } // Do not use a stale notoptions/alloptions cache when writing the marker. wp_cache_delete('vasp_prefix_migration_version', 'options'); wp_cache_delete('notoptions', 'options'); wp_cache_delete('alloptions', 'options'); if (!update_option('vasp_prefix_migration_version', '1', false) && get_option('vasp_prefix_migration_version', '') !== '1') { throw new RuntimeException('marker_failed'); } unset($GLOBALS['vasp_prefix_migration_error']); return true; } catch (Throwable $vasp_error) { $GLOBALS['vasp_prefix_migration_error'] = 'legacy_prefix_migration_failed'; return false; } finally { foreach (array_unique($vasp_cache_keys) as $vasp_cache_key) { wp_cache_delete($vasp_cache_key, 'options'); } if ($vasp_locked) { wp_cache_delete('alloptions', 'options'); wp_cache_delete('notoptions', 'options'); $wpdb->get_var($wpdb->prepare('SELECT RELEASE_LOCK(%s)', $vasp_lock)); } } } /** Install exact-key external-cache fallbacks without copying or extending TTL. */ function vasp_prefix_migration_transient_fallbacks(array $vasp_legacy_keys): void { if (!wp_using_ext_object_cache()) { return; } static $vasp_registered = []; foreach (array_unique($vasp_legacy_keys) as $vasp_old) { if (!vasp_prefix_migration_owned($vasp_old, 'transient')) { continue; } $vasp_new = 'vasp_' . substr($vasp_old, 3); if (isset($vasp_registered[$vasp_new])) { continue; } $vasp_registered[$vasp_new] = true; add_filter('pre_transient_' . $vasp_new, function ($vasp_pre) use ($vasp_old, $vasp_new) { if ($vasp_pre !== false) { return $vasp_pre; } $vasp_found = false; wp_cache_get($vasp_new, 'transient', false, $vasp_found); return $vasp_found ? false : get_transient($vasp_old); }); // WP invokes these hooks for both DB and external-cache transients. // This action fires only after a successful cache/database write. add_action('set_transient_' . $vasp_new, function () use ($vasp_old) { delete_transient($vasp_old); }); add_action('delete_transient_' . $vasp_new, function () use ($vasp_old) { delete_transient($vasp_old); }); } }