# Selective Thumbnail Regenerator

A WordPress plugin that allows users to regenerate thumbnails for media files uploaded in specific months and years - with advanced filtering, performance tuning, and full regeneration history tracking.

## Description

The Selective Thumbnail Regenerator plugin provides a powerful and user-friendly way to regenerate image thumbnails for WordPress media libraries. Unlike other thumbnail regeneration plugins that blindly process the entire library, this plugin gives you precise control: choose a specific year, month, and even a title keyword to target exactly the images you need.

### Key Features

- **Date & Title Filters** - Choose a specific year, month, or search by title to target only the images you need.
- **Month Status Calendar** - A visual 4×3 calendar appears when you select a year. Green months are verified full-month, all-size runs with no failures; legacy 1.0.4 records are retained in amber because their original scope cannot be verified.
- **Regeneration History Tracking** - Bounded job summaries store the exact filters, selected sizes, result counts, and completion status. A single "Reset History" button clears all records when needed.
- **Thumbnail Size Selection** - Choose specific registered thumbnail sizes to regenerate instead of processing all sizes.
- **Customizable Batch Size** - Configure how many images are processed per AJAX request (1-20) to suit your server's capacity.
- **Throttle Delay Control** - Set a cooldown pause between batches (0-2000 ms) to prevent server CPU overload.
- **Dry Run Mode** - Verify that every matching source exists, is readable, and can be opened by a WordPress image editor without writing changes.
- **Stable Server Jobs** - Each run uses a user-scoped, time-limited server job with a fixed upper attachment ID and an ID cursor, avoiding duplicate or endless offset processing when the media library changes.
- **Reload Recovery** - An unfinished job is detected when the admin page is reopened and can be resumed from its last per-image server checkpoint or cancelled safely.
- **Smart Regeneration** - A paginated preflight identifies missing, dimensionally incorrect, and stale sizes, reports how many files need work, estimates output size, and regenerates only that subset.
- **Automatic Batch Failure Recovery** - Progress is checkpointed before every image. If a batch request is interrupted, the plugin retries one image at a time, records the interrupted image, and continues.
- **Failed Images Log** - After completion, a detailed table lists every image that failed, including its ID, title, and exact failure reason.
- **Safe Orphaned File Cleanup** - Old thumbnail files are deleted only after replacement files and metadata are saved successfully.
- **Live Terminal Activity Log** - A real-time monospace console streams timestamped status messages for every operation during the regeneration process.
- **Visual Completion Metrics** - A five-card summary board displays totals for Processed, Successful, Failed, Skipped, and Duration.
- **Performance Optimized** - Uses a direct indexed `$wpdb` SQL query to populate the year selector, eliminating slowdowns on large media libraries.
- **Cancel Support** - Stop the regeneration safely after the current server step and receive an accurate partial summary.

---

## Installation

1. Download the plugin ZIP file.
2. Log in to your WordPress admin panel.
3. Go to **Plugins > Add New > Upload Plugin**.
4. Upload the ZIP file and click **Install Now**.
5. Activate the plugin through the **Plugins** menu in WordPress.

---

## Usage

1. Navigate to **Tools > Selective Thumbnail Regenerator** in your WordPress admin.
2. **Select a year** from the dropdown. A Month Status Calendar will appear showing which months have already been regenerated.
3. Optionally select a month - either via the dropdown or by clicking a month badge on the calendar.
4. Optionally enter a title keyword to filter images by name.
5. In the Performance Configuration card, adjust the batch size and throttle delay for your server.
6. Enable **Dry Run Mode** if you want to preview results without making changes.
7. Click **Scan Matching Images** to count matching images. With Smart Regeneration enabled, this performs a paginated preflight and estimates the required thumbnail work and output size.
8. Click **Start Regeneration** to begin. Watch the live terminal log for real-time updates.
9. After completion, review the Job Completion Report and, if any images failed, expand the Failed Images Log.

---

## Requirements

- WordPress 5.5 or higher
- PHP 7.0 or higher

---

## Frequently Asked Questions

### Why would I need to regenerate thumbnails?

You might need to regenerate thumbnails if:
- You've changed your theme and it uses different thumbnail sizes
- You've modified the thumbnail sizes in WordPress settings
- You've installed a plugin that adds new thumbnail sizes
- Your thumbnails are corrupted or missing

### Will this plugin delete my original images?

No. The plugin only regenerates thumbnail versions. Your original uploaded images are never touched.

### What does "orphaned file cleanup" mean?

When thumbnail dimensions change and you regenerate, the old thumbnail files (e.g. `image-300x200.jpg`) can remain on disk. The plugin compares old and newly saved metadata, then deletes only files that are no longer referenced. Existing files remain intact if generation or metadata saving fails.

### What happens if an image file is missing from the server?

The plugin detects that the original file is missing, marks it as failed in the log, and moves on to the next image. It never stops the entire regeneration process because of a single missing file.

### What happens if a server error occurs mid-batch?

The plugin automatically enters single-retry mode: it re-processes each image in the failed batch individually. The image causing the crash is identified, logged in the Failed Images report, and skipped so the rest can complete successfully.

### How does Dry Run Mode work?

When Dry Run is enabled, the plugin checks that each matching source exists, is readable, and can be opened by a WordPress image editor. It does not regenerate thumbnails or write to disk. The run is recorded as a dry-run job but never marks a calendar month complete.

### What is the Month Status Calendar?

It is a 4×3 grid of month buttons displayed beneath the date filter. A month turns green only after an unfiltered, all-size run finishes without failures or skips. Records created by older plugin versions appear in amber because their scope was not recorded. You can reset the history at any time with the "Reset History" button.

### Can I cancel the process?

Yes. Click the **Cancel Process** button that appears during regeneration. The active server step completes safely, then the process stops and displays a partial summary.

### What happens if I close the browser during regeneration?

The browser-driven processing loop pauses. Reopen the plugin page within 24 hours and use **Resume Job** to continue from the last per-image server checkpoint, or cancel the saved job. Completed work remains applied.

### What does Smart Regeneration check?

For each matching source image, Smart Regeneration compares active WordPress image sizes with saved metadata and files. It selects sizes whose file is missing, whose saved dimensions differ from the currently registered dimensions, or whose file is older than the source image. The preflight estimate is approximate and represents expected generated output, not guaranteed net disk growth.

---

## Troubleshooting

### "No images found for the selected period"

There are no image attachments in your media library uploaded during the selected year/month. Try a different time period.

### The process is slow

Reduce the throttle delay or increase the batch size in the Performance Configuration card if your server can handle more load. Alternatively, increase the delay and reduce the batch size if you are getting timeouts.

### A batch keeps failing

Enable Dry Run Mode first to verify that images and their files are accessible. If specific images crash the server, they will be listed in the Failed Images Log after regeneration completes.

---

## Changelog

### 1.1.2
- **Compatibility:** Pass prepared-query replacements as individual arguments so WordPress Plugin Check can validate all placeholders.

### 1.1.1
- **Compatibility:** Refactored attachment database reads into fixed prepared queries accepted by WordPress Plugin Check.
- **Security:** Switched AJAX nonce validation to the standard `check_ajax_referer()` flow and documented verified request reads.
- **Internationalization:** Added translator context for every localized string containing replacement placeholders.

### 1.1.0
- **Feature:** Detect and resume unfinished user jobs after the plugin page is reopened.
- **Feature:** Added a safe saved-job cancellation path and refreshed active-job expiry on every checkpoint.
- **Feature:** Added paginated Smart Regeneration preflight for missing, dimensionally incorrect, and stale thumbnail sizes.
- **Feature:** Added affected-image, thumbnail-count, and estimated-output-size metrics before regeneration.
- **Performance:** Smart mode regenerates only the sizes identified by a fresh per-image analysis.
- **Cleanup:** Uninstall now removes active-job and Smart-scan transient records in addition to job history and locks.

### 1.0.5
- **Reliability:** Replaced full-library offset scans with user-scoped transient jobs, stable ID cursors, immutable upper ID bounds, and per-image checkpoints.
- **Data Safety:** Generate and save replacement metadata before deleting obsolete thumbnails; preserve existing references for failed sizes.
- **History Accuracy:** Added versioned job history and verified calendar rules. Legacy completion flags remain visible as unverified amber records.
- **Security:** Removed dynamic HTML insertion for attachment titles and server messages in the admin interface.
- **Bug Fixes:** Fixed 0 ms throttle, title-only search, misleading success summaries, dry-run source checks, and safe cancellation behavior.
- **Accessibility:** Added native month and collapse buttons, focus states, ARIA expansion/selection states, a live progress status, and an activity log.
- **Internationalization:** Moved client-visible status and error text into localized WordPress strings.

### 1.0.4
- **Critical Fix:** Fixed fatal AJAX error by conditionally loading `wp-admin/includes/image.php` before calling `wp_generate_attachment_metadata()`.
- **Performance Fix:** Replaced PHP loop-based year extraction with a single fast `$wpdb` SQL query.
- **Bug Fix:** Allow thumbnail generation for attachments with missing or corrupt database metadata (graceful empty-array fallback).
- **Cleanup:** Implemented physical deletion of orphaned thumbnail files before regeneration.
- **Feature:** Month Status Calendar - visual 4×3 grid showing regenerated months per year, persisted in the database.
- **Feature:** Regeneration History Tracking with a "Reset History" button.
- **Feature:** Image title search filter.
- **Feature:** Dry Run Mode.
- **Feature:** Configurable Batch Size slider (1-20).
- **Feature:** Configurable Throttle Delay slider (0-2000 ms).
- **Feature:** Automatic batch failure recovery - retries each image individually when a batch crashes.
- **Feature:** Failed Images Log - detailed table of all images that failed with exact error reasons.
- **Redesign:** Full UI overhaul with Inter font, card layout, custom progress bar, live terminal console, and metrics board.

### 1.0.3
- Feature: Thumbnail size selection - choose which specific sizes to regenerate
- Feature: Cancel button - stop the regeneration process at any time
- Feature: Batch processing - process multiple images per AJAX request
- Feature: Summary report - view success/failure counts and elapsed time

### 1.0.2
- Security: Added capability checks to AJAX handlers
- Removed unnecessary plugin assets
- Code structure improvements

### 1.0.1
- Security: Added ABSPATH protection
- Compatibility: Updated "Tested up to" to WordPress 6.8
- Code Standards: Changed all prefixes from `str` to `strgrtr`
- Updated main class name to `STRGRTR_Thumbnail_Regenerator`

### 1.0.0
- Initial release

---

## License

This plugin is licensed under the GPL v2 or later.

## Credits

Developed by Redberet - [https://rberet.com](https://rberet.com) - Adi Glibanovic.
