# Changelog

All notable changes to Swish Migrate and Backup will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [1.4.0] - 2026-08-03

### Added
- **Full translations for Spanish (es_ES), French (fr_FR), Simplified Chinese (zh_CN), and Arabic (ar).** All 908 strings translated; `.po`/`.mo` files are bundled in `languages/`. Japanese (ja) remains available as a translate.wordpress.org language pack.
- Bundled translations are loaded via `load_plugin_textdomain()` on `init`; wordpress.org language packs still take priority when installed.

## [1.3.1] - 2026-07-14

### Changed
- **The plugin now activates without the mysqli PHP extension.** SQLite-based environments (WordPress Playground, WordPress Studio) lack mysqli, and the hard activation block prevented translators from previewing the UI via the translate.wordpress.org Playground link. mysqli was removed from the hard-required extension list (`zip` and `json` remain required); when it is missing, a warning notice on the plugin's admin pages explains that backup, restore, and migration features require a MySQL/MariaDB database.

### Fixed
- **Literal `%` characters in database content leaked into backups as `{64-hex}` placeholder tokens.** All four SQL dump writers (backup engine, export, multisite shared/site tables) escaped values with `$wpdb->_real_escape()`, whose output contains WordPress's placeholder-escape token for every literal `%` — core only strips it when a query executes, never in dump text. Restoring such a backup persisted the token into post content and corrupted serialized options (broken `s:N:` length prefixes → `unserialize()` failures, e.g. a `%s %v` currency format fataling a destination plugin on PHP 8). Values are now passed through `$wpdb->remove_placeholder_escape()` before being written.

## [1.3.0] - 2026-07-13

### Fixed
- **Multisite migration imports failed with repeated 500/403 errors** and never reported completion, even when the import had actually finished. Three root causes, all fixed:
  - The database restore overwrites `wp_usermeta`, invalidating the admin session's nonce so every progress poll returned 403. The progress handler now verifies the nonce softly and falls back to a read-only response gated by the unguessable job UUID, so the browser still receives the final status after its session is gone (also registered the `nopriv` AJAX variant).
  - Import progress was stored only in a transient inside `wp_options` — the very table the restore replaces — so progress was lost. Progress is now mirrored to `wp-content/swish-backups/temp/import-job-{id}.json` and read from there first.
  - Half-restored tables can fatal other destination plugins (500s) during the restore window. The progress dialog now tolerates 5xx/network errors for up to ~6 minutes once the restore has started, showing a "site may be briefly unreachable" message instead of failing after 3 attempts.

## [1.1.11] - 2026-05-27

### Changed
- **SWISH is now the only archive format** for new backups - removed Archive Format selector from Settings page
- Settings save handler (admin form + REST API) always stores `archive_format = 'swish'`

### Fixed
- **Windows copy/paste of curl and aria2c download commands** - commands were generated with backslash line continuations (POSIX shell syntax), causing CMD/PowerShell to parse each line as a separate command. Commands are now generated as a single line that copies as one command on bash, zsh, PowerShell and CMD

### Notes
- Restore still supports existing `.zip` and `.tar.gz` backups - underlying archiver/extractor classes remain in place

## [1.1.10] - 2026-05-18

### Fixed
- **PHP 7.4 compatibility** - converted `match` expressions to `switch` statements for broader PHP version support
- **Cancel job button** - now always cleans up localStorage even when server returns "job not found"
- **Stale jobs in UI** - polling error handler now properly removes job cards from UI when jobs not found on server

### Added
- Debug logging for backup progress troubleshooting (console messages with `[SwishBackup]` prefix)

## [1.1.9] - 2026-05-18

### Added
- **SWISH archive format option** in Settings dropdown - our custom streaming format with true append support and resume capability

## [1.1.8] - 2026-05-13

### Fixed
- **Missing files in backups** (e.g., uploads/2026 folder) - removed timeout checks during file indexing phase
- File enumeration now completes fully before archiving begins (AI1WM approach)
- Only memory pressure triggers yielding during indexing, not time limits
- **Job steps log not updating** during pipeline backups - now correctly shows phases
- Steps log displays pipeline phases: Scanning files → Archiving files → Finalizing
- Initial steps now displayed immediately when backup starts
- **Path resolution for symlinks and Docker** - improved `get_relative_path()` with realpath matching for plugins, themes, uploads, and wp-content directories
- **Plugin vendor directories not backed up** - removed `vendor` from default exclusions (was breaking plugins like Yoast Duplicate Post, WooCommerce that use Composer autoloaders)

### Changed
- **Backup size limit increased** from 2GB to 4GB for free version

### Added
- **Settings button on Backups page** for quick access before creating backups
- New settings modal with performance controls and hosting presets
- Quick presets for Shared Hosting, VPS/Managed, and Dedicated servers
- Backup contents toggles (Database, Plugins, Themes, Uploads, Core Files)
- CLI mode for BackupPipeline that disables time-based yielding
- `is_cli()` detection in ServerLimits class

### Changed
- **CLI backup performance** - now uses pipeline approach with optimized settings
  - Batch size increased to 500 files per iteration (no HTTP timeout concerns)
  - Disabled time-based yielding - only yields on memory pressure
  - Files write completely without internal chunking
  - Per-file logging reduced from info to debug level
- **Browser backup optimization** - dynamic settings based on server capabilities
  - Dynamic time budget using 60% of max_execution_time (10-25s range)
  - Adaptive batch size via ServerLimits detection for different hosts
  - Default batch size increased from 50 to 100 files per request
  - Automatic tuning for WP Engine, Kinsta, Flywheel, and managed hosts
- **Simplified settings UI** - consolidated to key settings: Files per Request, Database Rows per Batch
- Import pipeline reliability improvements
  - Fixed race condition in file queue processing
  - Increased stale session timeout from 2 to 10 minutes
  - Added database index on `updated_at` for faster queries
  - Fixed table prefix detection from SQL header comment
  - Added table prefix verification after database restore
- Performance optimizations
  - Chunked URL replacement prevents timeouts on large databases
  - Transient deletion loop limited to 100k iterations
  - URL replacement processes tables incrementally with state persistence
- Detailed migration progress indicators
  - Human-readable phase labels (e.g., "Restoring Database")
  - Progress shows actual data: bytes processed, tables imported, files copied
  - Finalize phase lists actions taken

### Added (Shared Components)
- `CacheManager` class for centralized cache operations with safeguards
- `count_tables_in_sql()` helper for accurate table counting

### Added (WP-CLI)
- `wp swish backup` command for creating backups from command line
- `wp swish import` command for importing/migrating backups via CLI
- `wp swish status` and `wp swish cleanup` utility commands
- CLI commands support all backup types: full, database, files

## [1.1.7] - 2026-05-12

### Fixed
- **Large file downloads now work with curl/wget** - moved download handler outside wp-admin
- Download URLs now use token-based authentication without requiring WordPress login
- Downloads support resumable transfers (`curl -C -` flag works correctly)
- **LiteSpeed X-LiteSpeed-Location disabled** - falls back to PHP streaming for reliable Range request support
- **Resumable downloads on GoDaddy/LiteSpeed + Cloudflare** - HTTP/2 stream resets no longer break downloads
- **Download tokens no longer deleted prematurely** - allows proper resume after connection failure

### Changed
- Download hook changed from `admin_init` to `init` (runs before WordPress admin auth)
- Download URLs changed from `/wp-admin/admin.php?...` to `/?swish_download=...`
- Removed `current_user_can()` check from download handler (token IS the authentication)
- LiteSpeed server detection returns false in `get_sendfile_method()` forcing PHP streaming fallback
- Download transient preserved until natural expiration (1 hour) instead of deleted after headers sent

## [1.1.6] - 2026-05-12

### Added
- REST API endpoints for schedule management (`/schedule/{id}/toggle`, `/schedule/{id}/run`, `/schedule/{id}/delete`)
- "Schedule Backup" button to empty state on Schedules page
- Scheduler dependency injection into RestController

### Fixed
- **Scheduled backups UI now fully functional** - toggle, run, and delete buttons work
- Backup job step indicators now show progress correctly (phase derived from progress percentage)
- JavaScript handlers now call actual API endpoints instead of stub implementations

## [1.1.5] - 2026-05-11

### Added
- **X-Sendfile/X-Accel-Redirect support** for large file downloads - bypasses PHP completely for file transfer
  - Apache: Uses `mod_xsendfile` when available
  - Nginx: Uses `X-Accel-Redirect` with configurable internal location
  - LiteSpeed: Uses `X-LiteSpeed-Location` (built-in support)
  - Automatic fallback to PHP streaming when not available
- HTTP Range request support for resumable backup downloads (4GB+ files)
- Chunked file streaming for downloads (8MB chunks) to avoid memory exhaustion
- `Accept-Ranges: bytes` header for browser download resume support
- New "Logs" admin page for viewing and managing backup logs
- Logging toggle (default: OFF) to enable/disable log collection
- Log level filter (All, Error, Warning, Info, Debug)
- Delete all logs functionality with file and database cleanup
- `Logger::is_enabled()` static method to check logging status

### Fixed
- Large backup downloads (4GB+) failing due to memory exhaustion or timeout
- Browser unable to resume interrupted backup downloads
- Migration import rejecting .tar.gz and .swish files (now accepts ZIP, TAR.GZ, SWISH)
- Migration analysis failing for .tar.gz backups (was only reading ZIP format)
- Restore process failing for .tar.gz backups (added PharData extraction support)
- **Files not being restored from streaming tar backups** - restore now handles direct file extraction (wp-content, wp-includes, etc. extracted directly instead of nested in files.tar.gz)
- **Backup verification failing for renamed files** - WordPress may rename uploaded files (e.g., `.tar.gz` → `.tar-2.gz`), now uses magic byte detection for reliable format identification
- **CRITICAL: Backups losing folder structure on Docker/symlink setups** - `get_relative_path()` now properly handles WP_CONTENT_DIR, WP_PLUGIN_DIR, theme root, and uploads when they resolve to different paths than ABSPATH (common in Docker, ddev, symlinked setups)

### Changed
- Download handler now streams files in chunks instead of using `readfile()`
- Download token preserved until full download completes (allows resume)
- Logger now checks if logging is enabled before writing entries

## [1.1.3] - 2026-05-11

### Added
- Chunked database backup with checkpoint support for large sites
- `DatabaseBackup::backup_chunked()` method for resumable database backups
- 25-second time slices for database backup (up from 10s, with max_execution_time=300)
- Database backup continuation support via `continue_database_backup()`
- Full progress tracking for database backup (table-by-table progress)
- Keyset pagination for database queries (O(1) instead of O(n) per batch)
- Primary key detection for automatic keyset pagination selection
- Multi-chunk processing: runs ~10 chunks per request before yielding to cron
- Extended INSERT syntax with multiple value tuples for fewer SQL statements

### Fixed
- Database backup timing out on large sites (100k+ rows in tables like `postmeta`)
- 77+ tables being skipped due to timeout on large WooCommerce/blog sites
- Backup appearing to complete but missing most database tables
- Database backup not resuming properly after timeout
- Checkpoint not saving database-specific fields (`db_file`, `db_checkpoint`, `backup_type`)
- Misleading "Async backup completed" log when continuation is scheduled
- WP-Cron not triggering continuation reliably (added fallback via status polling)
- Frontend showing stale "X/Y tables" message during large table processing
- Slow database backup due to OFFSET pagination causing O(n²) row scans
- Excessive cron overhead from yielding after every 25-second chunk

### Changed
- `run_full_backup_streaming()` now uses chunked database backup with multi-chunk loop
- `run_database_backup()` now uses chunked database backup with multi-chunk loop
- `continue_database_backup()` runs multiple chunks per request (up to 270s before yield)
- Database backup saves checkpoint after each table for reliable resumption
- Default batch size increased from 200 to 1000 rows per query (5x faster)
- Database queries use `WHERE pk > last_pk` instead of `OFFSET` for large tables
- Time slice increased from 10s to 25s per chunk for better throughput

## [1.1.2] - 2026-05-08

### Added
- New `StreamingTarBackup` class for true streaming file backups
- Pure PHP tar creation - works in all environments (Docker, ddev, managed hosts)
- 10-second time slices with automatic state persistence and continuation
- 1MB file chunk reads - never loads more than 1MB into memory
- USTAR tar format with extended header support for long filenames (>100 chars)
- Streaming gzip compression after tar completion

### Fixed
- Full backups getting stuck at "Backing up files..." on large sites (50,000+ files)
- Memory exhaustion during file backup in Docker/ddev environments
- `should_use_tar()` returning false in containerized environments forcing memory-heavy ZIP mode
- Empty files (0 bytes) causing `fread()` error during streaming backup
- Missing `BackupState::delete_meta()` method causing backup completion to fail

### Changed
- `BackupManager::run_full_backup()` now always uses streaming tar (no more ZIP batch mode)
- File backups process files one at a time instead of loading entire lists into memory
- Backup continuation now handles `streaming_files` phase for seamless resumption

## [1.0.18] - 2026-04-30

### Fixed
- Plugins not activating when importing a single site from a multisite backup
- Network-activated plugins now captured in backup manifest for multisite exports

## [1.0.17] - 2026-04-21

### Fixed
- Duplicate "Migrate Site" card on dashboard
- REST API download route not matching backup IDs with underscores (e.g., `backup_uuid`)

### Changed
- Pipeline Batch Size defaults: Shared hosting (150), VPS (250), Dedicated server (500)

## [1.0.16] - 2026-04-21

### Fixed
- Critical bug: ServerLimits timing check caused immediate yield due to int/float comparison (`0 === 0.0` is false in PHP 8)
- Files stuck in 'processing' status now reset to 'pending' for retry
- Reduced stale processing threshold from 300s to 30s for faster recovery
- Partial file resume corruption - files now restart from scratch instead of attempting resume

### Added
- Detailed logging for file processing: batch info, file status, yield reasons
- Context data now included in log file output for better debugging

### Changed
- Overall progress calculation now includes all phases (indexing 0-10%, processing 10-95%, finalizing 95-100%)

## [1.0.15] - 2026-04-21

### Added
- Archive format setting (Auto/ZIP/TAR.GZ) in settings page
- Streaming file scanning for large sites (writes to disk, not memory)
- Memory-efficient tar creation using `--files-from` for 50k+ files
- Docker/ddev environment detection with automatic ZIP fallback
- CPU/IO throttling with `nice` and `ionice` for tar operations

### Fixed
- Backup failing at 70% on large sites (2GB+) due to memory exhaustion
- Server crashes during archive creation in containerized environments
- Timeout issues during file staging step

### Changed
- Tar backups now skip staging step entirely (direct archive from source)
- File list written to disk instead of held in memory
- Fast GZIP compression (level 1) for better performance
- Auto-fallback to ZIP if tar fails or times out

## [1.0.12] - 2026-04-20

### Changed
- Dashboard now has three action boxes: Backup Now, Search & Replace, and Migrate Site
- Renamed "Migrate Site" panel to "Search & Replace" for clarity
- Added dedicated "Migrate Site" button linking to the migration page

## [1.0.11] - 2026-04-20

### Fixed
- Vendor folders are now included in backups (previously excluded, causing plugin errors after migration)

## [1.0.10] - 2026-04-20

### Added
- Memory-aware adaptive batch sizing for database and file backups
- Memory-aware adaptive batch sizing for URL search/replace during migration
- Automatic batch size reduction when memory pressure is detected
- Stream-based ZIP extraction to prevent memory exhaustion on large backups
- Memory threshold monitoring (32MB) to trigger adaptive processing
- User-friendly error messages for server limit errors (memory, timeout, upload size)
- Pre-import memory check with clear warning if insufficient memory available
- Shutdown handler to catch and report fatal errors during import/migration

### Fixed
- Memory exhaustion during import/restore of large backups (now uses streaming extraction)
- Import failing with `wp_handle_upload()` undefined function error
- Large file extraction causing PHP memory limit errors
- Fatal errors during import now show helpful messages instead of silent failures
- Connection reset during "Updating URLs" phase on memory-constrained servers
- Connection reset during "Finalizing" phase caused by pre-migration backup creation

### Changed
- ZIP extraction now reads files in 8KB chunks instead of loading entire files into memory
- Database backup automatically reduces batch size when memory is low
- File backup flushes ZIP archive more frequently under memory pressure
- File backup progress now shows percentage instead of time estimation
- URL search/replace now processes 100 rows per batch (reduced from 500)
- Transient cache clearing now uses batched deletion (1000 at a time)
- Pre-migration backup is now opt-in to avoid memory exhaustion during migration

## [1.0.9] - 2026-04-20

### Added
- Async backup processing to prevent timeouts on managed hosting (WP Engine, Flywheel, etc.)
- Background job processing via WP Cron with automatic fallback for hosts with alternate cron
- Job status polling endpoint (`/job/{id}/process`) for triggering pending backups directly
- Real-time progress updates during backup process
- ETA (estimated time remaining) display during file backup showing files processed and time remaining

### Fixed
- Backup download returning "0" - changed from admin-ajax.php to admin.php endpoint
- Added proper download handler with token validation and security checks

### Changed
- Backup API now uses async processing by default
- Frontend polling improved with automatic fallback when WP Cron doesn't trigger

## [1.0.8] - 2026-04-15

### Fixed
- Replaced inline `<script>` tag with `wp_add_inline_script()` for WordPress.org compliance
- Replaced `move_uploaded_file()` with `wp_handle_upload()` for proper WordPress file handling

## [1.0.7] - 2026-02-25

### Changed
- Compatibility update for Pro plugin import fixes
- Minor stability improvements

## [1.0.6] - 2026-02-25

### Changed
- Compatibility update for Pro plugin URL auto-detection fixes
- Minor stability improvements

## [1.0.5] - 2026-02-25

### Changed
- Compatibility update for Pro plugin size estimation fixes
- Minor stability improvements

## [1.0.4] - 2026-02-25

### Changed
- Compatibility update for Pro plugin import/migration fixes
- Minor stability improvements

## [1.0.3] - 2026-02-25

### Added
- Auto-detection of old site URL during migration (pre-filled from backup manifest)
- Detailed migration progress with stage tracking similar to backup process
- Smooth scrolling and active state highlighting for documentation navigation
- REST endpoint for importing backup files (`/swish-backup/v1/import`)

### Changed
- Moved backup storage location from `wp-content/uploads/swish-backups/` to `wp-content/swish-backups/`
- Improved documentation page with better anchor link navigation

### Fixed
- Import feature Continue button now properly uploads and analyzes backup files
- Backup exclusion now always excludes swish-backups folder from backups
- Prevents backups from including previous backup archives

## [1.0.2] - 2025-02-25

### Added
- Enhanced backup progress modal with detailed stage tracking
- Visual progress log showing each backup stage as it completes
- Green checkmarks for completed stages
- Red indicators for failed stages
- Animated spinner for in-progress stages

### Changed
- Improved progress feedback during backup process
- Better error handling and messaging

### Fixed
- Minor UI improvements for progress display

## [1.0.1] - 2025-02-20

### Added
- Option to include/exclude WordPress core files in backups

### Changed
- Enhanced CSS for admin layout with responsive design
- Refactored JavaScript asset enqueuing for improved performance

### Fixed
- Minor bug fixes and improvements

## [1.0.0] - 2025-02-15

### Added
- Initial release
- Full site backup support (database, plugins, themes, uploads)
- Database-only backup option
- Files-only backup option
- Local storage adapter
- Amazon S3 storage adapter
- Dropbox storage adapter
- Google Drive storage adapter
- Site migration with automatic URL replacement
- Search and replace functionality with serialization support
- Scheduled backups (hourly, daily, weekly, monthly)
- Chunked processing for large sites
- AES-256-CBC encrypted cloud storage credentials
- Full REST API for integration
