$definition]; $resources[] = array_merge([ 'owner' => $owner, 'storage' => $storage, 'key' => (string) $overrides['key'], 'autoload' => $storage === 'option' ? $autoload : null, 'reset' => (bool) $reset, 'uninstall' => (bool) $uninstall, ], $overrides); } return $resources; } /** Return the authoritative inventory of ValueSpace-owned WordPress state. */ function vasp_state_manifest() { return [ 'core' => array_merge( vasp_state_resources('core', 'option', [ ['key' => VASP_OPTION_VERSION, 'reset' => false], ['key' => 'vasp_prefix_migration_version', 'reset' => false], ['key' => 'vasp_prefix_migration_transients', 'reset' => false], ['key' => VASP_OPTION_INSTALLED, 'reset' => false], ['key' => VASP_VALUESPACE_WAS_CONNECTED, 'reset' => false], ['key' => VASP_OPTION_STATE_SCHEMA_VERSION, 'reset' => false], ['key' => VASP_OPTION_TENANT_ID, 'reset' => false], VASP_OPTION_ENCRYPTION_KEY, ['key' => VASP_OPTION_WIDGET_POSITION, 'reset' => false], ['key' => VASP_OPTION_WIDGET_THEME, 'reset' => false], ['key' => VASP_OPTION_WIDGET_DISABLED_POST_TYPES, 'reset' => false], ['key' => VASP_OPTION_WIDGET_SITE_VISIBILITY, 'reset' => false], VASP_OPTION_SYNC_RECONCILIATION_LAST_STARTED, VASP_OPTION_SYNC_RECONCILIATION_LAST_COMPLETED, ], true, true, false), vasp_state_resources('core', 'transient', [ VASP_TRANSIENT_ACTIVATION_REDIRECT, VASP_TRANSIENT_ADMIN_NOTICE, VASP_TRANSIENT_BILLING_SUMMARY_CACHE, VASP_TRANSIENT_GATEWAY_UNREACHABLE, ]), vasp_state_resources('core', 'dynamic_transient_prefix', [VASP_TRANSIENT_NOTICE_SUPPRESSED_PREFIX]), vasp_state_resources('core', 'wp_cron', ['vs_monitor_scheduled_tasks']) ), 'connections' => array_merge( vasp_state_resources('connections', 'option', [ VASP_VALUESPACE_CONNECTED_TIME, VASP_VALUESPACE_AVAILABILITY_OPTION, VASP_VALUESPACE_LAST_ERROR, VASP_VALUESPACE_DENIED, VASP_VALUESPACE_CLIENT_ID, VASP_OPTION_CLIENT_SECRET, VASP_OPTION_REFRESH_TOKEN, VASP_WORDPRESS_CONNECTED_TIME, VASP_WORDPRESS_LAST_ERROR, VASP_WORDPRESS_DENIED, VASP_WOOCOMMERCE_CONNECTED_TIME, VASP_WOOCOMMERCE_LAST_ERROR, VASP_WOOCOMMERCE_DENIED, VASP_OPTION_SSO_SECRET, VASP_OPTION_SSO_SECRET_ESTABLISHED_AT, VASP_OPTION_SSO_SECRET_ROTATED_AT, VASP_OPTION_TOKEN_REFRESH_LOCK, VASP_OPTION_TOKEN_REFRESH_FAILURES, VASP_OPTION_TOKEN_LAST_REFRESH, VASP_OPTION_WORDPRESS_INDEXATION_TRIGGERED, VASP_OPTION_WORDPRESS_INGESTION_STATUS, VASP_OPTION_WORDPRESS_SYNC_COMPLETED_TIME, ], true, true, false), vasp_state_resources('connections', 'transient', [ VASP_OPTION_CONNECTION_STATUS, VASP_OPTION_REQUIRED_SCOPES, VASP_TRANSIENT_PKCE_VERIFIER, VASP_TRANSIENT_ACCESS_TOKEN, VASP_TRANSIENT_TOKEN_EXPIRES_AT, VASP_TRANSIENT_TOKEN_REFRESH_COOLDOWN, VASP_TRANSIENT_TOKEN_REFRESH_RETRY_AFTER, 'vasp_code_verifier', VASP_TRANSIENT_REFRESH_TOKEN_EXPIRES_AT, ]), vasp_state_resources('connections', 'dynamic_transient_prefix', [ VASP_TRANSIENT_BOOTSTRAP_NONCE_PREFIX, VASP_TRANSIENT_VASP_REGISTRATION_STATE, VASP_TRANSIENT_VASP_AUTHORIZATION_STATE, 'vasp_wordpress_callback_state_', 'vasp_woocommerce_callback_state_', 'vasp_valuespace_bootstrap_callback_state_', ]), // Keep the retired refresh hook so reset/uninstall removes stale upgrades. vasp_state_resources('connections', 'wp_cron', [ 'vs_refresh_tokens', VASP_ACTION_RETRY_USER_ACCESS_REVOCATION, ]) ), 'catalog' => array_merge( vasp_state_resources('catalog', 'option', array_merge([ VASP_OPTION_WC_CATALOG_STATUS, VASP_OPTION_WC_CATALOG_PENDING_MODE, VASP_OPTION_WC_CATALOG_LAST_ERROR, VASP_OPTION_WC_CATALOG_PUSH_ENABLED, VASP_OPTION_WC_CATALOG_SYNC_COMPLETED_TIME, VASP_OPTION_WC_CATALOG_STEP, VASP_OPTION_WC_CATALOG_PROGRESS, ], VASP_WC_CATALOG_RETIRED_OPTIONS), true, true, false), // An explicit connection reset recreates catalog receipt and queue state. vasp_state_resources('catalog', 'option', [ VASP_OPTION_WC_CATALOG_STORAGE_SCHEMA, ], true, true, false), vasp_state_resources('catalog', 'feature_cleanup', [[ 'key' => 'catalog_delivery_storage', 'file' => 'includes/catalog/storage.php', 'uninstall_callback' => 'vasp_wc_catalog_uninstall_storage', ]], true, true), // Cleanup only for retired hook retries and option outboxes. vasp_state_resources('catalog', 'dynamic_transient_prefix', ['vs_wc_rt_retry_']), vasp_state_resources('catalog', 'dynamic_option_prefix', ['vs_wc_rt_outbox_']), vasp_state_resources('catalog', 'wp_cron', [ VASP_ACTION_WC_CATALOG_PUSH_REFRESH, 'vs_wc_catalog_feed', 'vs_wc_catalog_realtime_retry', 'vs_woocommerce_image_sync_daily', ]) ), 'contact_form' => vasp_state_resources('contact_form', 'dynamic_transient_prefix', [ 'vasp_contact_rate_', ]), 'events' => array_merge( vasp_state_resources('events', 'option', array_merge([ VASP_EVENT_SETTINGS_OPTION, VASP_EVENT_TRACKING_CONFIGURATION_OPTION, ['key' => VASP_EVENT_STORAGE_SCHEMA_OPTION, 'reset' => false], VASP_EVENT_INDEX_BACKFILL_OPTION, VASP_EVENT_LAST_CRON_RUN_OPTION, VASP_EVENT_DELIVERY_STATUS_OPTION, VASP_EVENT_DELIVERY_GENERATION_OPTION, VASP_EVENT_DELIVERY_LOCK_OPTION, ], VASP_EVENT_LEGACY_OPTIONS), false, true, false), vasp_state_resources('events', 'transient', array_merge([ VASP_EVENT_TRACKING_CONFIGURATION_TRANSIENT, ], VASP_EVENT_LEGACY_TRANSIENTS), false, true), vasp_state_resources('events', 'dynamic_transient_prefix', [ 'vasp_event_rate_', 'vasp_session_', ], false, true), vasp_state_resources('events', 'dynamic_option_prefix', [ 'vasp_event_session_lock_', 'vasp_event_abandon_lock_', ], false, true), // Keep the retired domain cron here so reset/uninstall clears upgrades. // vasp_deliver_events remains the bounded raw-event outbox worker. vasp_state_resources('events', 'wp_cron', ['vs_process_events', 'vasp_deliver_events']), vasp_state_resources('events', 'feature_cleanup', [[ 'key' => 'indexed_event_storage', 'file' => 'includes/events/storage.php', 'reset_callback' => 'vasp_event_reset_indexed_storage', 'uninstall_callback' => 'vasp_event_uninstall_indexed_storage', ]], false, true) ), 'scheduler' => array_merge( vasp_state_resources( 'scheduler', 'dynamic_option_prefix', ['vasp_sync_pending_', 'vasp_sync_running_', 'vasp_sync_dispatching_'] ), vasp_state_resources('scheduler', 'wp_cron', [ 'vasp_run_sync_service', 'vasp_reconcile_sync_jobs', ]) ), // Keep this group last: dynamic-transient cleanup needs the registry // entries before the registry options themselves are removed. 'state_registry' => vasp_state_resources( 'core', 'dynamic_option_prefix', ['vasp_dynamic_transient_key_'] ), ]; } /** Return the exact registry option used for one dynamic transient. */ function vasp_state_dynamic_transient_registry_key($transient) { return 'vasp_dynamic_transient_key_' . hash('sha256', (string) $transient); } /** * Store a dynamic transient and register its exact key for object-cache-safe cleanup. * * @return bool */ function vasp_set_dynamic_transient($transient, $value, $expiration) { $transient = (string) $transient; if ($transient === '' || !set_transient($transient, $value, (int) $expiration)) { return false; } $registry_key = vasp_state_dynamic_transient_registry_key($transient); if (!update_option($registry_key, $transient, false) && get_option($registry_key, null) !== $transient ) { delete_transient($transient); return false; } return true; } /** Delete one registered dynamic transient. */ function vasp_delete_dynamic_transient($transient) { $transient = (string) $transient; delete_transient($transient); delete_option(vasp_state_dynamic_transient_registry_key($transient)); } /** Delete options whose names begin with one exact plugin-owned prefix. */ function vasp_state_delete_option_prefix($prefix) { global $wpdb; $names = $wpdb->get_col($wpdb->prepare( 'SELECT option_name FROM %i WHERE option_name LIKE %s', $wpdb->options, $wpdb->esc_like((string) $prefix) . '%' )); foreach ((array) $names as $name) { // WordPress option tables commonly use a case-insensitive collation. if (strpos((string) $name, (string) $prefix) === 0) { delete_option($name); } } } /** Delete many cache keys with a fallback for object-cache implementations. */ function vasp_state_delete_cache_keys(array $keys, $group) { foreach (array_chunk(array_values(array_unique($keys)), 500) as $chunk) { if (function_exists('wp_cache_delete_multiple')) { wp_cache_delete_multiple($chunk, (string) $group); continue; } foreach ($chunk as $key) { wp_cache_delete($key, (string) $group); } } } /** * Bulk-delete transients whose names begin with plugin-owned prefixes. * * Dynamic transient registries are filtered in SQL once. Database-backed * transient rows are removed in one query instead of invoking delete_option() * several times per transient, which becomes prohibitively slow for large * event-session collections. * * @return array|WP_Error Cleanup counters or an error. */ function vasp_state_delete_transient_prefixes(array $prefixes) { global $wpdb; $prefixes = array_values(array_unique(array_filter(array_map('strval', $prefixes), 'strlen'))); if (empty($prefixes)) { return [ 'transients_deleted' => 0, 'database_rows_deleted' => 0, 'registry_rows_deleted' => 0, ]; } // Dynamic transients may live only in an external object cache. Their // exact names are therefore indexed in ordinary non-autoloaded options. $registry_prefix = 'vasp_dynamic_transient_key_'; $registry_conditions = implode(' OR ', array_fill(0, count($prefixes), 'option_value LIKE %s')); $registry_args = [$wpdb->options, $wpdb->esc_like($registry_prefix) . '%']; foreach ($prefixes as $prefix) { $registry_args[] = $wpdb->esc_like($prefix) . '%'; } $registry_rows = $wpdb->get_results($wpdb->prepare( "SELECT option_name, option_value FROM %i WHERE option_name LIKE %s AND ({$registry_conditions})", $registry_args ), ARRAY_A); if ($wpdb->last_error) { return new WP_Error('vasp_transient_registry_read_failed'); } $transients = []; $registry_option_names = []; foreach ((array) $registry_rows as $row) { $transient = maybe_unserialize($row['option_value'] ?? ''); if (!is_string($transient)) { continue; } foreach ($prefixes as $prefix) { if (strpos($transient, $prefix) === 0) { $transients[$transient] = true; $registry_option_names[] = (string) $row['option_name']; break; } } } $database_conditions = []; $database_args = [$wpdb->options]; foreach ($prefixes as $prefix) { $database_conditions[] = 'option_name LIKE %s'; $database_args[] = $wpdb->esc_like('_transient_' . $prefix) . '%'; $database_conditions[] = 'option_name LIKE %s'; $database_args[] = $wpdb->esc_like('_transient_timeout_' . $prefix) . '%'; } $database_where = implode(' OR ', $database_conditions); // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter -- WHERE contains only literal placeholder clauses; the table uses %i and all prefixes use esc_like and prepare below. $names = $wpdb->get_col($wpdb->prepare( "SELECT option_name FROM %i WHERE {$database_where}", $database_args )); if ($wpdb->last_error) { return new WP_Error('vasp_transient_rows_read_failed'); } $database_option_names = []; foreach ((array) $names as $name) { $transient = strpos($name, '_transient_timeout_') === 0 ? substr($name, strlen('_transient_timeout_')) : substr($name, strlen('_transient_')); foreach ($prefixes as $prefix) { if (strpos($transient, $prefix) === 0) { $transients[$transient] = true; $database_option_names[] = (string) $name; break; } } } // Delete only the option names that passed the case-sensitive PHP prefix // check. wp_options normally uses a case-insensitive collation, so the // discovery LIKE can return differently cased, unrelated rows. $database_rows_deleted = 0; foreach (array_chunk(array_values(array_unique($database_option_names)), 500) as $chunk) { $placeholders = implode(', ', array_fill(0, count($chunk), '%s')); $deleted = $wpdb->query($wpdb->prepare( "DELETE FROM %i WHERE option_name IN ({$placeholders})", array_merge([$wpdb->options], $chunk) )); if ($deleted === false) { return new WP_Error('vasp_transient_rows_delete_failed'); } $database_rows_deleted += (int) $deleted; $deleted_transients = []; foreach ($chunk as $option_name) { $deleted_transients[] = strpos($option_name, '_transient_timeout_') === 0 ? substr($option_name, strlen('_transient_timeout_')) : substr($option_name, strlen('_transient_')); } // Keep already-deleted chunks unreadable from a persistent object // cache even if a later database chunk fails. vasp_state_delete_cache_keys($deleted_transients, 'transient'); vasp_state_delete_cache_keys($chunk, 'options'); } $transient_names = array_keys($transients); vasp_state_delete_cache_keys($transient_names, 'transient'); vasp_state_delete_cache_keys($database_option_names, 'options'); wp_cache_delete('alloptions', 'options'); // Delete only registry rows whose values passed the case-sensitive PHP // prefix check above. Typical wp_options collations make SQL LIKE // case-insensitive, so repeating the LIKE filter for deletion could remove // a differently cased, unrelated registry entry. $registry_rows_deleted = 0; foreach (array_chunk(array_values(array_unique($registry_option_names)), 500) as $chunk) { $placeholders = implode(', ', array_fill(0, count($chunk), '%s')); $deleted = $wpdb->query($wpdb->prepare( "DELETE FROM %i WHERE option_name IN ({$placeholders})", array_merge([$wpdb->options], $chunk) )); if ($deleted === false) { return new WP_Error('vasp_transient_registry_delete_failed'); } $registry_rows_deleted += (int) $deleted; vasp_state_delete_cache_keys($chunk, 'options'); } return [ 'transients_deleted' => count($transient_names), 'database_rows_deleted' => (int) $database_rows_deleted, 'registry_rows_deleted' => (int) $registry_rows_deleted, ]; } /** Delete transients whose names begin with one exact plugin-owned prefix. */ function vasp_state_delete_transient_prefix($prefix) { return vasp_state_delete_transient_prefixes([(string) $prefix]); } /** * Invalidate pending connection handshakes without deleting durable feature data. * * The keys come from the authoritative connection manifest. Durable credentials * and catalog/event state remain owned by their feature-specific reset paths. */ function vasp_cleanup_pending_connection_state() { $manifest = vasp_state_manifest(); foreach ((array) ($manifest['connections'] ?? []) as $resource) { $storage = (string) ($resource['storage'] ?? ''); $key = (string) ($resource['key'] ?? ''); if ($key === '') { continue; } if ($storage === 'transient') { delete_transient($key); } elseif ($storage === 'dynamic_transient_prefix') { if (is_wp_error(vasp_state_delete_transient_prefix($key))) { return false; } } } return true; } /** Clear every argument variant from WP-Cron. */ function vasp_state_clear_scheduled_hook($hook) { if (function_exists('vasp_scheduler_clear')) { vasp_scheduler_clear((string) $hook, null); } else { wp_clear_scheduled_hook((string) $hook); } if (wp_next_scheduled((string) $hook) !== false) { throw new RuntimeException('Scheduled hook cleanup failed: ' . (string) $hook); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal manifest hook; cleanup catches exceptions without displaying their messages. } } /** Run one feature-owned cleanup callback declared by the manifest. */ function vasp_state_run_feature_cleanup(array $resource, $scope) { $callback = isset($resource[$scope . '_callback']) ? (string) $resource[$scope . '_callback'] : ''; if ($callback === '') { return; } if (!function_exists($callback) && !empty($resource['file'])) { $file = dirname(__DIR__) . '/' . ltrim((string) $resource['file'], '/\\'); if (is_file($file)) { require_once $file; } } if (!function_exists($callback)) { throw new RuntimeException('Missing state cleanup callback: ' . $callback); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal manifest callback; cleanup catches exceptions without displaying their messages. } $result = call_user_func($callback); if ($result === false || is_wp_error($result)) { throw new RuntimeException('State cleanup callback failed: ' . $callback); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Internal manifest callback; cleanup catches exceptions without displaying their messages. } } /** * Enforce non-autoload policy for every exact option resource in the manifest. * * Directly updating the autoload column is required for WordPress 6.2 because * update_option() returns early when only autoload changes and the value is * unchanged. * * @return bool */ function vasp_state_enforce_autoload_policy() { global $wpdb; $success = true; $cache_changed = false; foreach (vasp_state_manifest() as $resources) { foreach ($resources as $resource) { if ($resource['autoload'] !== false || $resource['storage'] !== 'option' ) { continue; } $key = (string) $resource['key']; $updated = $wpdb->update( $wpdb->options, ['autoload' => 'no'], ['option_name' => $key], ['%s'], ['%s'] ); if ($updated === false) { $success = false; continue; } if ($updated > 0) { wp_cache_delete($key, 'options'); $cache_changed = true; } } } if ($cache_changed) { wp_cache_delete('alloptions', 'options'); } return $success; } /** * Clean plugin state according to the authoritative manifest. * * Reset preserves installation/version markers, administrator preferences, and * retained event data. Uninstall removes every declared resource. */ function vasp_cleanup_plugin_data($scope = 'reset') { static $completed = []; $scope = $scope === 'uninstall' ? 'uninstall' : 'reset'; if (!empty($completed[$scope])) { return true; } $failures = []; foreach (vasp_state_manifest() as $resources) { foreach ($resources as $resource) { if (empty($resource[$scope])) { continue; } try { $key = (string) $resource['key']; switch ($resource['storage']) { case 'option': delete_option($key); break; case 'transient': delete_transient($key); break; case 'dynamic_option_prefix': vasp_state_delete_option_prefix($key); break; case 'dynamic_transient_prefix': $result = vasp_state_delete_transient_prefix($key); if (is_wp_error($result)) { throw new RuntimeException('Dynamic transient cleanup failed: ' . $key); } break; case 'wp_cron': vasp_state_clear_scheduled_hook($key); break; case 'feature_cleanup': vasp_state_run_feature_cleanup($resource, $scope); break; } } catch (Throwable $error) { $failures[] = [ 'owner' => $resource['owner'], 'storage' => $resource['storage'], 'exception' => get_class($error), ]; } } } if (!empty($failures)) { vasp_log('ValueSpace state cleanup completed with failures', 'error', [ 'scope' => $scope, 'failures' => $failures, ]); return false; } $completed[$scope] = true; vasp_log('ValueSpace state cleanup completed', 'info', ['scope' => $scope]); return true; }