=== AI Bot & Traffic Analytics – Track AI Visits & Control AI Crawlers ===
Tags: ai, analytics, crawler, robots.txt, woocommerce
Requires at least: 6.5
Tested up to: 7.1
Requires PHP: 8.1
Stable tag: 0.3.0
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Track AI crawlers, referral visits, and AI-referred orders and revenue for WooCommerce stores. Control access for AI bots.

== Description ==

AI Bot & Traffic Analytics shows which known AI crawlers visit your site, which pages they read, and how many visitors AI tools such as ChatGPT, Perplexity, Gemini and Copilot send you. All data stays in your WordPress database.

When you want control, you choose a policy and the plugin turns it into robots.txt preferences and, if you enable it, into HTTP 403 responses for matching requests. You can block AI training crawlers and keep AI search crawlers allowed.

The plugin ships with a bundled catalog of 50 entries: 48 HTTP user-agent crawlers and clients plus 2 robots.txt usage-preference tokens. They are grouped into training crawlers, AI search crawlers, user-triggered fetchers, mixed-purpose crawlers, a protected group (for example Googlebot, Bingbot and social link preview bots) that is never blocked unless you override it explicitly, and non-AI entries (informational only). The catalog is part of the plugin release and is not downloaded.

**Observe mode is the default.** In Observe mode nothing is blocked and robots.txt is not changed. The plugin only records what a policy would have done. Enforce mode starts only after you switch to it.

= For WooCommerce stores =

The free plugin shows:

* AI bots on product pages.
* AI referral visits.
* AI orders and revenue for the last 30 days.

The Store edition adds per-product revenue, AI source details in the Orders list, and the bot-to-visit-to-order funnel.

= What it does =

* Policy presets: open, allow search but not training, and closed. Each preset sets an action for each crawler category.
* Per-crawler overrides, path rules (first matching rule wins) and a user-agent allowlist.
* robots.txt: adds a managed section for the crawlers in your policy to the robots.txt that WordPress generates. It also writes `Content-Usage` and `Content-Signal` preference lines, each of which can be turned off. A physical robots.txt file in the site root is not edited. The plugin shows a comparison with it instead.
* PHP-level blocking in Enforce mode: matching requests get a 403 response early in the WordPress load.
* Crawler verification for the vendors that publish IP ranges: a request is marked as verified only if its IP address is in the published ranges bundled with the plugin or refreshed from the vendor.
* Optional Cloudflare proxy trust, so that the visitor address is read correctly behind Cloudflare.
* Coverage checks: the plugin requests your own pages with a crawler user-agent to show whether the policy reaches them, including cached pages.
* Optional `.htaccess` rules for Apache and LiteSpeed, with a preview, a database-stored backup (up to 10 snapshots), a verification step and a rollback button. On LiteSpeed, the generated block also marks blocked crawler requests as non-cacheable (`Cache-Control:no-cache`). For nginx the plugin only shows a configuration snippet for you to review and apply yourself.
* Local activity log: crawler requests, the decision taken and the rule that caused it, with a "why" explanation per event. CSV export of the last seven days.
* Counts of human visits referred from a short list of AI assistants (`chatgpt.com`, `chat.openai.com`, `www.perplexity.ai`, `perplexity.ai`, `gemini.google.com`, `copilot.microsoft.com`). On uncached page loads this runs in PHP via the `Referer` header. For cached sites, an optional JavaScript beacon (**off by default**, opt-in in Settings) can count those referrals without cookies. Only a daily count per referrer host is stored.
* Policy revisions with conflict detection when two administrators save at the same time.
* WP-CLI commands under `wp ai-bot-control`: status, policy, simulate, server, coverage and catalog.

= What it cannot do =

PHP-level blocking runs inside WordPress. A page served by a page cache plugin, a CDN or a server rule before WordPress starts is not seen by it. The Coverage screen exists to show you this. The `.htaccess` option covers the Apache and LiteSpeed case, but it cannot cover a CDN or a cache in front of the server.

robots.txt is a request, not an enforcement mechanism. Crawlers may ignore it. A crawler that sends a false user-agent is not recognized.

The plugin does not claim legal protection of your content and does not provide legal advice.

== Installation ==

1. Upload the plugin folder to `/wp-content/plugins/`, or install it from the Plugins screen.
2. Activate the plugin. It creates its database tables and starts in Observe mode with the "allow search, no training" preset.
3. Open **AI Bot Analytics** in the admin menu. Review the policy and watch the Activity screen for a while.
4. Run the Coverage checks. When the result matches what you expect, switch the policy to Enforce.

The plugin requires PHP 8.1 or later and WordPress 6.5 or later. It needs the `vendor/` directory that is included in the release package. If you install from a source checkout, run `composer install --no-dev` first.

== Frequently Asked Questions ==

= Will it block Googlebot or Bingbot? =

No. Search engine crawlers and link preview bots are in a protected group that is always allowed. You can override this per crawler, but you have to do it on purpose. Verified search engine traffic is only affected if you change that setting.

= The default mode does nothing. Is it working? =

Yes. Observe mode records the decision the policy would have taken (shown as "would block") without sending any 403. Switch to Enforce when you are satisfied with the Activity screen.

= Does it change my robots.txt file? =

It changes the robots.txt that WordPress generates dynamically, and only in Enforce mode. If a physical robots.txt file exists in the site root, the web server serves that file and WordPress never sees the request. The plugin does not edit that file. The robots.txt preview shows what the file should contain to match your policy.

= Why are some crawlers still reaching my cached pages? =

A page cache or CDN can answer before WordPress runs, so PHP-level blocking does not apply. Use the Coverage screen to check, and consider the `.htaccess` option, a rule in your CDN or a rule in your web server.

= Is it safe to let the plugin write to .htaccess? =

Nothing is written without your confirmation. The flow is:

1. You open a preview of the exact block that will be added and a diff against the current file.
2. When you confirm, the plugin stores a copy of the original file in the database, writes a marked block (`# BEGIN AI Bot & Traffic Analytics` ... `# END AI Bot & Traffic Analytics`) and checks that the site still responds normally. If the check fails, it removes the block again.
3. You can roll back at any time with the Restore action. It removes only the marked block, so changes made to the rest of the file by other tools after your deployment are kept.

Up to 10 backups are kept. The backup is the complete file contents as they were before the change. If you cannot reach wp-admin because of a server misconfiguration, remove the lines between the two marker comments by hand over FTP or SSH.

The option is offered only on Apache and LiteSpeed. While server rules are deployed, the plugin refuses to switch the policy out of Enforce mode until you roll them back. Deactivating the plugin does not remove the block from `.htaccess`. Roll back first, then deactivate.

= Does it support nginx? =

It generates a configuration snippet for you to read and apply yourself. It never writes nginx configuration.

= Does it work on multisite? =

Tables and settings are created per site on activation, and uninstall cleans each site. Multisite is not part of the tested configurations in this version.

= Does it slow my site down? =

For requests with an ordinary browser user-agent the plugin does a user-agent check against the catalog and returns. Logging of crawler requests happens at the end of the request.

= What happens to my data on uninstall? =

By default nothing is deleted. Turn on the delete-data-on-uninstall option in Settings if you want the tables, options and scheduled events removed when the plugin is deleted.

== External services ==

The crawler catalog and a snapshot of vendor IP ranges are bundled with each release. External requests described below are optional.

**Optional IP range refresh.** On the Settings screen an administrator can turn on a daily background update, or can request a single update manually. The setting is off by default. Nothing is requested on activation or on front-end page views. When an update runs, the plugin downloads the public IP range lists below with an HTTPS request. The request carries the web server's IP address (as for any HTTP connection) and the user-agent `AIBotCrawlerControl/0.1.0`. No visitor IP address, visitor request data, or site content is sent. A response that is invalid, too large or not HTTP 200 is discarded and the bundled or last valid snapshot stays in use. The bot catalog has no update service.

* OpenAI: `https://openai.com/gptbot.json`, `https://openai.com/searchbot.json`, `https://openai.com/adsbot.json` and `https://openai.com/chatgpt-user.json`. Used to verify OpenAI crawler requests. Terms: https://openai.com/policies/terms-of-use/ Privacy: https://openai.com/policies/privacy-policy/
* Google: `https://developers.google.com/static/crawling/ipranges/common-crawlers.json`, `https://developers.google.com/static/crawling/ipranges/special-crawlers.json` and `https://developers.google.com/static/crawling/ipranges/user-triggered-fetchers.json`. Used to verify Google crawler requests. Terms: https://developers.google.com/terms/site-terms Privacy: https://policies.google.com/privacy
* Perplexity: `https://www.perplexity.ai/perplexitybot.json` and `https://www.perplexity.ai/perplexity-user.json`. Used to verify Perplexity crawler requests. Terms: https://www.perplexity.ai/hub/legal/terms-of-service Privacy: https://www.perplexity.ai/hub/legal/privacy-notice
* Apple: `https://search.developer.apple.com/applebot.json`. Used to verify Applebot requests. Terms: https://www.apple.com/legal/internet-services/terms/site.html Privacy: https://www.apple.com/legal/privacy/
* Cloudflare: `https://www.cloudflare.com/ips-v4` and `https://www.cloudflare.com/ips-v6`. These two lists are refreshed together during an IP range update and are used to validate proxy headers only if an administrator has turned on Cloudflare proxy trust. Terms: https://www.cloudflare.com/terms/ Privacy: https://www.cloudflare.com/privacypolicy/

Anthropic does not publish machine-readable crawler IP ranges, so the plugin does not request anything from Anthropic. ClaudeBot requests are matched by user-agent only, because there is no published list to check the address against.

**Requests to your own site.** All diagnostic and referral-counting HTTP requests stay on your own site and never contact third parties:

* The Coverage checks and the robots.txt preview send HTTP loopback requests to your own `home_url()` with a test user-agent (for example `AIBCC-Coverage/1.0`) and a request path. Administrators start them by opening the Coverage/Settings screens or running a coverage test.
* For a site in a subdirectory, Coverage also requests `/robots.txt` at the root of the site's own domain to check its crawler rules. The response is cached for about 12 hours; an administrator can request a fresh check.
* The optional cached-page AI referral beacon (off by default; enabled manually in Settings → General & Privacy) loads `assets/public/referral-beacon.js` on public pages. It checks `document.referrer` and the `utm_source` query parameter locally against the supported AI hostnames (`chatgpt.com`, `chat.openai.com`, `www.perplexity.ai`, `perplexity.ai`, `gemini.google.com`, `copilot.microsoft.com`). If there is no match, no network request is made. When matched, it sends a same-origin `POST` request to your own site's REST endpoint (`/wp-json/aibcc/v1/referral-beacon`) containing only `{ "source": "<ai-host>", "path": "<pathname>" }` (query strings and URL fragments are stripped). No cookies, `localStorage`, `sessionStorage`, or user identifiers are used. Pages cached before enabling the setting will include the script only after the page cache refreshes; when the setting is off, the REST endpoint returns HTTP 403.

== Privacy ==

The plugin stores activity data in your own database. Nothing is sent to the developer when you deactivate the plugin.

Recorded for crawler requests only (requests whose user-agent matches the bundled catalog): time, request path, crawler identity, the decision taken and the policy revision, and an IP address. By default the address is masked (IPv4 /24, IPv6 /48). In Settings you can switch to a keyed hash of the address. Ordinary visitors are not logged.

For human visits that arrive from a supported AI assistant (`chatgpt.com`, `chat.openai.com`, `www.perplexity.ai`, `perplexity.ai`, `gemini.google.com`, `copilot.microsoft.com`), the plugin increments only a daily aggregate counter per AI source host (`category = 'referral'`). On uncached requests this uses the HTTP `Referer` header in PHP. If you manually enable the opt-in JavaScript referral beacon (off by default), the front-end script sends only the matched AI host and page pathname (without query parameters or fragments) to your own site's REST API (`/wp-json/aibcc/v1/referral-beacon`) without reading or setting cookies, `localStorage`, or `sessionStorage`. Neither the page path nor the visitor IP address is stored in the analytics table for these referral visits; short-lived transients (30–60 seconds) used for deduplication and rate limiting store only keyed HMAC-SHA256 digests (`wp_salt('auth')`), never raw IP addresses.

Retention: detailed events are kept for 7 days and daily aggregates for 30 days by default. Both periods are configurable in Settings and are enforced by a daily scheduled task.

A saved policy can contain allowlist entries entered by an administrator. If server rules are deployed, up to 10 copies of the `.htaccess` file are kept in the database for rollback.

Because crawler visits are recorded together with an IP address, you may need to mention this in your own privacy policy. This is not legal advice.

== Screenshots ==

1. Overview with seven-day crawler traffic and the current mode.
2. Crawler policy: presets, category actions, per-crawler and path rules.
3. Coverage checks showing which layers apply the policy.
4. Activity log with the "why" explanation for a decision.
5. Settings: retention, IP storage, background updates, Cloudflare trust.
6. Overview card with AI-referred WooCommerce orders and revenue for the last 30 days.

== Source code and build ==

The PHP source is included in the plugin. Both the admin scripts in `assets/admin/` and the opt-in referral beacon script `assets/public/referral-beacon.js` are plain JavaScript files shipped unminified, with no build step. Composer is used only for the PHP autoloader (`composer install --no-dev`).

== Changelog ==

= 0.3.0 =
* New: `aibcc_catalog_data` and `aibcc_ip_ranges_snapshot` filters let add-ons supply catalog and IP range data. Invalid data falls back to the bundled catalog.
* Improved: IP verification no longer re-validates the whole range list on every check.
* Fixed: an error in a third-party verification provider filter no longer breaks the request.

= 0.2.0 =
* New: WooCommerce card with AI-referred orders and revenue for the last 30 days.
* New: sites installed in a subdirectory get a check of the root robots.txt and a ready block to copy there.
* Improved: friendly names for AI referral sources, Cloudflare coverage status, Activity table layout.

= 0.1.0 =
* Initial release.
