=== Naibabiji Cache Purger for EdgeOne ===
Contributors: Naibabiji
Tags: edgeone, cache, purge, cdn, tencent cloud
Requires at least: 5.0
Tested up to: 6.9
Stable tag: 2.3.1
Requires PHP: 7.2
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Automatically purge Tencent Cloud EdgeOne cache when WordPress posts are published, updated, or deleted.

== Description ==

A powerful WordPress plugin that automatically purges Tencent Cloud EdgeOne cache when your posts, pages, or custom post types are published, updated, or deleted.

== External services ==

This plugin connects to the Tencent Cloud EdgeOne API (https://teo.tencentcloudapi.com) to provide cache purging and prefetching functionality. 

It sends the Following information to Tencent Cloud when a purge or prefetch operation is triggered (e.g., when a post is updated, or when manual purge is used):
*   Tencent Cloud API Credentials (SecretId): Used for request authentication and signing.
*   EdgeOne Zone ID: Used to identify the specific site/zone in EdgeOne.
*   Target URLs or Paths: The specific resources that need to be cleared or prefetched from the CDN nodes.

This service is provided by "Tencent Cloud": [Terms of Service](https://cloud.tencent.com/document/product/301/127483), [Privacy Policy](https://cloud.tencent.com/document/product/301/11470).

== Features ==

= Automatic Cache Purge =
* Automatically purges cache when posts are published, updated, or deleted
* Supports all public post types (posts, pages, and custom post types)
* Smart purge: automatically refreshes post pages, homepage, category archives, tag archives, author archives, and date archives

= Comment Integration =
* Automatically purges related post cache when new comments are approved

= Manual Purge =
* Support for manual purge of specific posts or entire site
* Quick purge buttons in admin panel for recent posts

= Flexible Configuration =
* Choose purge method: delete cache (delete) or mark as expired (invalidate)
* Optional logging of purge operations
* Secure key configuration via wp-config.php constants

= Cache Plugin Integration =
* Automatically purges EdgeOne cache when popular WordPress cache plugins clear their cache
* Supports WP Super Cache, W3 Total Cache, WP Rocket, and LiteSpeed Cache
* Force mode ensures cache plugin integrations work even when auto purge is disabled
* Proper timing control ensures compatibility with all cache plugin loading sequences

= Cache Prefetching =
* Optional cache prefetching after purging (disabled by default)
* Only prefetches post URLs, not archive pages to conserve EdgeOne prefetch quota
* Ensures first visitor gets cached content immediately
* Prefetch results are displayed in the purge logs for easy monitoring

= Enhanced Logging =
* Detailed logging of all purge operations with success/failure status
* Manual log clearing functionality for easier debugging
* Prefetch operation results displayed alongside purge results
* Job IDs and error messages for easy troubleshooting

= Advanced Manual Purge =
* Optimized host-specific "Purge All" using the purge_host method
* Manual purge operations are not affected by auto purge settings
* Force mode support for cache plugin integrations
* Comprehensive URL coverage for post-related purges

= Custom URL Purge =
* Purge cache for specific URLs (CSS, JS, images, etc.)
* Support for directory prefix purge using trailing slash (/)
* Batch processing: enter multiple URLs, one per line
* Automatic URL validation and filtering
* Smart type detection: files use purge_url, directories use purge_prefix

= Nginx Cache Integration =
* Optionally clear Nginx server-side page cache (FastCGI cache or Proxy cache) alongside EdgeOne CDN cache
* Configured separately — most sites using only WordPress cache plugins do not need this
* Nginx cache and EdgeOne cache are cleared independently; either can succeed even if the other fails
* Includes path validation with real-time feedback in the settings page
* Uses ngx_cache_purge module for precise URL-based cache clearing (faster and more efficient)
* Added "Purge Endpoint Path" option for customizable Nginx purge URL path (e.g., use a random string like /xK9mPurge_q7z for better security)
* Uses HTTPS requests to your site's own domain for purge, avoiding HTTP-to-HTTPS redirect issues
* Friendly error messages in purge logs: clearly explains why a URL wasn't cached (e.g., "Not cached — the page was returned instead of a purge response") instead of showing raw HTML
* Fallback to file deletion for full-site purge operations
* Detailed per-URL purge logging for Nginx cache operations

= No SDK Required =
* Direct API calls, no need to install Tencent Cloud SDK
* Compatible with all WordPress versions 5.5+

== Installation ==

= Method 1: Upload =

1. Download the plugin zip file
2. Log in to WordPress admin dashboard
3. Go to "Plugins" → "Add New" → "Upload Plugin"
4. Select and upload the plugin zip file
5. Activate the plugin

= Method 2: Manual Installation =

1. Upload the plugin folder to the `wp-content/plugins/` directory
2. Log in to WordPress admin dashboard
3. Go to "Plugins" page
4. Find "Naibabiji Cache Purger for EdgeOne" plugin and activate it

== Configuration ==

= Get Tencent Cloud API Keys =

1. Visit [Tencent Cloud Console](https://console.cloud.tencent.com/cam/capi)
2. Create or get your `SecretId` and `SecretKey`

= Get EdgeOne Zone ID =

1. Visit [EdgeOne Console](https://console.cloud.tencent.com/teo)
2. Select your site and find the Zone ID (format: zone-xxxxxx)

= Configure Plugin =

There are two configuration methods:

=== Method 1: Using wp-config.php (Recommended) ===

Add these constants to your WordPress `wp-config.php` file:

	define( 'NB_CACHE_PURGER_SECRET_ID', 'your-secret-id' );
	define( 'NB_CACHE_PURGER_SECRET_KEY', 'your-secret-key' );

Then in WordPress admin:
1. Go to "Settings" → "Naibabiji Cache Purger"
2. Fill in the **Zone ID** (Secret ID and Secret Key will be automatically loaded from constants)
3. Choose other options and save

=== Method 2: Direct Configuration in Admin ===

1. Log in to WordPress admin
2. Go to "Settings" → "Naibabiji Cache Purger"
3. Fill in the following information:
   * **Secret ID**: Tencent Cloud API Secret ID
   * **Secret Key**: Tencent Cloud API Secret Key
   * **Zone ID**: EdgeOne Zone ID
4. Choose other options:
   * **Enable Auto Purge**: Whether to automatically purge cache when posts are updated
   * **Purge Method**:
     * `delete`: Directly delete node cache
     * `invalidate`: Mark as expired, revalidate from origin
   * **Enable Logging**: Whether to log purge operations

= Nginx Cache Integration (Optional) =

Only needed if your server uses Nginx FastCGI cache or Proxy cache (configured via `fastcgi_cache_path` or `proxy_cache_path` in nginx.conf). Most sites using WordPress cache plugins do not need this.

1. In "Settings" → "Naibabiji Cache Purger" → scroll to the **Nginx Cache Integration** section at the bottom
2. Check **Enable Nginx Cache Purge**
3. Set a **Purge Endpoint Path** — we recommend using a random string (e.g., `/xK9mPurge_q7z`) for security, so you can use `allow all;` in Nginx without exposing the endpoint to attackers
4. Enter the absolute filesystem path to your Nginx cache zone directory (e.g. `/var/run/nginx-cache`) — this is only used as fallback when purging the entire site
   * The web server process (e.g. `www-data`) must have write permission to this directory
   * The settings page will validate the path and show whether it is writable
5. Save settings — Nginx cache will now be cleared automatically every time EdgeOne cache is purged

= Nginx Purge Configuration =

To use the ngx_cache_purge module integration, you need to configure your Nginx server block with the appropriate purge rules. Replace `/xK9mPurge_q7z` with your custom purge path:

	nginx
	location ~ /xK9mPurge_q7z(/.*) {
	    allow all;
	    deny none;
	    fastcgi_cache_purge YOUR_CACHE_ZONE "https$request_method$host$1";
	    # Or for proxy cache:
	    # proxy_cache_purge YOUR_CACHE_ZONE "https$request_method$host$1";
	}


Replace `YOUR_CACHE_ZONE` with the name of your Nginx cache zone (e.g., `wordpress`).

**Important notes:**
* The `fastcgi_cache_purge` key (`"https$request_method$host$1"`) must match your `fastcgi_cache_key` directive exactly, including the `https` prefix
* If you are using BT Panel (宝塔) with an HTTP-to-HTTPS redirect rule, the plugin sends HTTPS requests to your own domain, so no additional exclusion rules are needed
* For detailed configuration instructions, see the [configuration tutorial](https://www.quhenet.com/bt-panel-nginx-fastcgi/)

== Frequently Asked Questions ==

= What is EdgeOne? =

EdgeOne is Tencent Cloud's edge computing and CDN service that provides global content delivery and security features.

= Why do I need to purge cache? =

When you update content on your WordPress site, EdgeOne may serve cached versions. This plugin ensures visitors see the latest content immediately.

= Is this plugin secure? =

Yes, the plugin supports storing API credentials in wp-config.php, keeping them out of the database and admin interface.

= What URLs are purged when a post is updated? =

The plugin automatically purges:
* The post/page URL
* Homepage
* Category archives the post belongs to
* Tag archives the post has
* Author archive
* Date-based archives

= Do I need the Nginx Cache Integration? =

No, it is optional. Only enable it if your server uses Nginx-level page caching (FastCGI cache or Proxy cache). If you use WordPress cache plugins such as WP Rocket, W3 Total Cache, or LiteSpeed Cache, you do not need this feature.

= What is the difference between Nginx cache and EdgeOne CDN cache? =

EdgeOne CDN cache is distributed across edge nodes worldwide and is managed via the Tencent Cloud API. Nginx cache is a server-side page cache stored on your own server's filesystem, managed by Nginx's `fastcgi_cache` or `proxy_cache` directives. They are separate caching layers; this plugin can clear both at the same time.

= Why does the plugin keep the Nginx cache directory itself instead of deleting and recreating it? =

Deleting and recreating the directory creates a brief window where Nginx may fail to write new cache entries. By only deleting the contents and keeping the directory, the purge is safer and avoids potential Nginx errors.

= The Nginx cache path shows "not writable" — how do I fix it? =

The PHP process (typically `www-data` or `nginx`) needs write permission on the cache directory. Run `chown www-data:www-data /your/cache/path` or `chmod 755 /your/cache/path` as appropriate for your server setup.

== Screenshots ==

1. Plugin settings page - Configure your EdgeOne credentials and purge options
2. Quick purge buttons - Manual purge options for recent posts
3. Log viewer - View detailed purge operation logs

== Changelog ==

= 2.3.1 =
* Fixed async purge not executing — multiple root causes addressed:
  - Switched async task data storage from transient to wp-option to prevent data loss when object cache (Redis/Memcached) evicts keys
  - Removed 5-second scheduling delay that caused trigger_cron() to fire before tasks were due
  - Fixed trigger_cron() setting doing_cron transient that blocked server-side cron from running
  - Uses spawn_cron() by default; falls back to direct non-blocking HTTP request to wp-cron.php when DISABLE_WP_CRON is set
* Fixed purge logs not being recorded when object cache evicts transients — switched log storage from transient to wp-option
* Added async task health monitoring: stuck tasks are detected and executed synchronously as recovery
* Added auto-degradation from async to sync mode with admin notice when WP-Cron is broken
* Added purge lock check in health recovery to prevent duplicate API calls
* Extended health check threshold to 15 minutes when DISABLE_WP_CRON is set (to accommodate server cron intervals)

= 2.3.0 =
* Enhanced Nginx cache purge functionality: Replaced recursive file deletion with ngx_cache_purge module HTTP requests for precise URL-based clearing
* Added per-URL purge logging for Nginx cache operations
* Added "Test Nginx Purge Connection" button in settings to verify ngx_cache_purge module configuration
* Implemented fallback to file deletion for full-site purge operations
* Improved Nginx purge error handling and status reporting

= 2.2.0 =
* Improved "Purge All" behavior: It now only clears the cache for the current site's hostname (using purge_host) instead of the entire zone. This prevents unintentional cache clearing of other subdomains sharing the same EdgeOne Zone ID.

= 2.1.0 =
* Complete rebranding: Renamed plugin to Naibabiji Cache Purger for EdgeOne.
* Deep refactoring of all internal classes, namespaces, and file structures for better maintenance.
* Switched all internal database option keys to standardized lowercase `nb_cache_purger_` prefix.
* Updated all hooks, transients, and nonces to use unified `nb_cache_purger_` branding.
* Improved security and trademark compliance.

= 2.0 =
* Complete code refactoring with modern PHP namespace architecture
* Added asynchronous purge mode support (configurable via settings)
* Added purge statistics dashboard showing total purges, success rate, and breakdown by reason
* Enhanced log sanitization to protect sensitive API credentials
* Improved admin bar menu with parent-child structure (EdgeOne → Purge All / Settings)
* Enhanced security: sensitive input fields hidden when constants are defined in wp-config.php
* Modular code structure for better maintainability and extensibility
* Improved error handling and detailed API response logging
* Updated UI/UX to match 1.4 interface while maintaining 2.0 functionality
* Restored Chinese translations for all interface elements
* Added settings entry on plugin list page
* Improved manual purge interface with separate sections for Post ID and Custom URLs
* Enhanced logging with better error messages and request tracking

= 1.4 =
* Added Nginx server-side cache integration (FastCGI cache / Proxy cache)
* Nginx cache path is validated in real time on the settings page (existence, writeability)
* Nginx cache and EdgeOne CDN cache are cleared independently — failure of one does not block the other
* Nginx purge result is recorded in the purge log when logging is enabled
* New settings are disabled by default and clearly marked as optional to avoid confusion for users who do not use Nginx cache
* Added Settings shortcut link on the Plugins list page
* Added EdgeOne node to the admin bar with quick Purge All Cache and Settings links

= 1.3 =
* Improved localization and language files

= 1.2 =
* Added custom URL purge functionality for static resources (CSS, JS, images)
* Added directory prefix purge support using trailing slash (/)
* Fixed cache plugin hook detection logic
* Improved timing control for plugin initialization
* Enhanced manual purge with full site purge support
* Added force mode for cache plugin integrations
* Improved logging with prefetch result display
* Added manual log clearing functionality
* Fixed X-TC-Timestamp header type safety
* Updated WordPress 6.0+ compatibility
* Enhanced settings descriptions for clarity

= 1.1 =
* Added cache plugin integration (WP Super Cache, W3 Total Cache, WP Rocket, LiteSpeed Cache)
* Added optional cache prefetching functionality
* Improved error handling and logging

= 1.0 =
* Initial release
* Automatic cache purge on post publish/update/delete
* Manual purge functionality
* Comment integration
* Flexible configuration options
* Logging support

== Upgrade Notice ==

= 2.3.1 =
Critical fix for async purge mode: tasks were not executing due to transient data loss, scheduling timing conflicts, and cron lock interference. If you use async mode, this update is strongly recommended.

= 2.3.0 =
Enhanced Nginx cache purge with ngx_cache_purge module, custom random endpoint paths, and HTTPS-based purge requests. Update your Nginx configuration with the new purge path. See settings page for details.

= 2.0 =
Major update with complete code refactoring, asynchronous mode support, statistics dashboard, and enhanced security. Backup your settings before upgrading.

= 1.4 =
Adds optional Nginx server-side cache integration. Disabled by default — no action needed unless your server uses Nginx FastCGI or Proxy cache.

= 1.3 =
* Improved localization and language files

= 1.2 =
* Cache plugin integrations now work correctly with proper hook detection
* Manual purge now supports host-specific "Purge All" using the purge_host method
* Added manual log clearing functionality for easier debugging
* Improved compatibility with WordPress 6.0+ and various PHP versions

= 1.1 =
* Added cache plugin integration and optional prefetching functionality

= 1.0 =
Initial release - No upgrade required