=== D Analytics ===
Contributors: dsolutions
Requires at least: 6.4
Tested up to: 7.1
Requires PHP: 8.1
Stable tag: 1.1.0
License: GPL-3.0-or-later
License URI: https://www.gnu.org/licenses/gpl-3.0.html

Privacy-first, cookieless-by-default analytics for WordPress.

== Description ==

D Analytics is a privacy-first statistics plugin for a single WordPress site. It counts visits on your own server, shows them in a fast dashboard inside wp-admin and sends nothing to a third party.

* Cookieless by default: visitors are told apart by a hash that changes every day and is never stored with an IP address or a user agent.
* Consent aware: it follows the WP Consent API, Google Consent Mode v2 (`analytics_storage`) or `dAnalytics.setConsent()`, uses a cookie only after consent and can fall back to counting pageviews only.
* Light: a tracker of about 1.7 KB gzipped, a one-minute aggregation job, and an optional optimized endpoint that answers a visit without loading WordPress.
* Traffic channels, named as in Google Analytics 4 (Direct, Organic Search, Paid Search, Organic Social, Email, AI Assistant, Referral and more): entrances, visitors, pageviews and share of entrances, with Vietnamese services (Zalo, Messenger, Cốc Cốc, Shopee, Lazada) and AI assistants recognised.
* Dashboard: visitors and pageviews with the change against the previous period, pages, referrers (with Vietnamese services such as Zalo, Cốc Cốc and TikTok grouped), browsers, operating systems, devices, countries, campaigns (utm_source, utm_medium, utm_campaign) and custom events.
* Everywhere: a pageviews column in the post list, an admin bar sparkline, a dashboard widget, two blocks and shortcodes, AMP support and WP-CLI commands (`wp help d-analytics`).
* Email: optional weekly and monthly reports and traffic spike alerts.
* Importers for Koko Analytics, Plausible, Burst Statistics, WP Statistics, Independent Analytics, Statify and SlimStat.
* English and Vietnamese, including Vietnamese referrer rules.
* Every feature is built in; there are no licence keys and no upsell.

D Analytics is a derivative work of Koko Analytics by Danny van Kooten (ibericode), licensed under GPL-3.0-or-later (https://github.com/ibericode/koko-analytics). The referrer blocklist is copied from Koko Analytics. See `THIRD-PARTY-NOTICES.txt` for the other components.

== Installation ==

= nginx: protect the data folder =

D Analytics stores its buffer and visitor-day files in `wp-content/uploads/d-analytics/`. Apache honours the `.htaccess` file the plugin creates there. nginx ignores it, so add this to the server block:

`location ^~ /wp-content/uploads/d-analytics/ { deny all; return 403; }`

(Use your real uploads path if it differs.) The daily secret is stored in a PHP file that never prints its content, and file names are random, but denying the folder keeps raw buffer files private.

= AMP pages =

With the AMP plugin active, AMP pages send their pageview through an `amp-analytics` request instead of the tracker script. AMP only allows HTTPS requests, so the site must be served over HTTPS for AMP pages to be counted. AMP has no consent adapter, so the "before consent" method (cookieless, or pageview-only in strict mode) is always used, and the "exclude this browser" switch cannot be read there.

= Custom events =

Settings, Tracking, Events. A new site starts with outbound links and the JavaScript API on and form submissions off; a site that is already running keeps what it has saved.

* JavaScript API: `dAnalytics.trackEvent( name, param, value )`. A name is short text of letters, marks, digits, punctuation, symbols and spaces ("Don’t", "A & B", "Buy now!" and emoji are fine; control characters are removed; 100 characters at most). `(other)`, `outbound_link` and `form_submit` are reserved. The parameter is free text (185 characters), the value an integer that is clamped to ±2147483647. Calls made before the script has loaded are queued, and `trackEvent` exists on every page (it does nothing where nothing is tracked), so theme code never throws. The call returns `true` when a beacon was sent, and `false` with one console warning when the name is refused. Do not put personal data (an email address, a name, an account id) in a name or parameter: both are stored and shown as they are.
* Outbound links: a click on an http(s) link to another host (the own host and its subdomains are internal) counts as `outbound_link` with the host and path as the parameter (or the host only, if you choose "Host only"). The query string and fragment are never sent. Links inside SVG graphics count too.
* Form submissions: a submit counts as `form_submit` with the form id, name or action path as the parameter. It counts when the visitor sends the form, even if the site then rejects it. Field values are never read. Search forms are skipped by default.
* Add the class `d-analytics-ignore` to a link or form (or an element around it) to leave it out.
* Events follow the pageview rules: excluded roles and IPs, the browser opt-out, bots and the consent mode. Under strict pre-consent counting, hits are counted and uniques are not.
* The events script is a separate file (about 0.9 KB gzipped) printed only while a feature is on. Each day keeps at most 100 distinct names (filter `d_analytics_event_daily_name_cap`) and, for each name, at most 200 distinct parameters (filter `d_analytics_event_daily_param_cap`). Names beyond the cap are grouped as "(other)", parameters beyond the cap as "(other)" under their name, so a flood of outbound links cannot push your own events out; every total stays exact. The name row of an event with several parameters shows "–" for Uniques, because a visitor who used two parameters is counted once for each; the parameter rows are exact. Use a few fixed parameters, not ids or search terms.
* Imports never contain events, so a replacing import leaves them untouched.

= Email reports and spike alerts =

Settings, Email (both off until you switch them on):

* Reports: a weekly (Monday) and/or monthly (the 1st) email at an hour of the site's time zone, covering the last finished week (honouring "Week starts on") or month. It holds visitors and pageviews with the change against the previous period (the same comparison as the dashboard), a daily bar chart, the top 10 pages and referrers, and the top 5 countries, campaigns and events when those features are on. The numbers come from the same queries as the dashboard.
* Each period is sent once. WP-Cron can run late or twice at the same time; a database lock (an options row, if the database cannot give a lock) and a record of who already has the period keep it to one email per address, and a late run sends the latest finished period only, never a backlog. An address is recorded before its message is handed over, so a failure halfway never mails anyone twice. Addresses that did not get it are tried again an hour later, and only they (three tries).
* Spike alerts: sent when the last hour has at least N times the usual hour (the median day of the previous days, up to 28, divided by 24; at least 7 days of statistics are needed) and at least the minimum number of pageviews. Once 7 days of daily peak hours are recorded, an hour must also be 1.5 times the median daily peak, so a site with a rush every office morning is not alerted every morning. One alert per spike: the next waits until traffic has dropped back and the cooldown has passed. The top pages and referrers in the alert cover the whole day so far, because statistics are kept per day. The check runs after each aggregation, at most once every 5 minutes; the email is sent by a separate cron event, and a send that reached nobody is not retried for an hour.
* Recipients are validated addresses (default: the site administrator). A recipient with a user account gets the email in the language of their profile; others get the site language. Emails are HTML with inline CSS and a plain-text part, and contain no images, scripts or tracking. The footer links to the settings screen, which needs a login: there is no public unsubscribe address. Remove an address in Settings, Email to stop its mail.
* "Send test report now" and "Send test alert now" send to your own address. `wp d-analytics report send --period=weekly|monthly [--to=<emails>] [--force] [--dry-run] [--yes]` sends through the same code as the schedule.
* Delivery depends on your host. Install an SMTP plugin if mail does not arrive; the last mail error is shown in Settings, Email. Without visitors WP-Cron does not run: call `wp-cron.php` from a real cron job.

== Frequently Asked Questions ==

= Do I need a cookie banner? =

By default no cookie is set and no IP address is stored. Whether counting without consent is acceptable depends on your jurisdiction: some data protection authorities treat any identifier derived from the visitor, even one that changes daily, as needing consent. For a conservative setup choose Settings, Tracking, "Before consent" = pageviews only; visitors are then not counted until the visitor agrees. This is not legal advice.

= How often are statistics updated? =

Visits are written to a buffer and added to the daily totals by a WP-Cron job every minute. WP-Cron runs when the site gets a request; on a quiet site call `wp-cron.php` from a real cron job (and optionally set `DISABLE_WP_CRON`). `wp d-analytics aggregate` runs the job by hand.

= The site runs on more than one server. =

The default buffer and visitor storage are files in `wp-content/uploads/d-analytics/`, which servers that do not share a disk cannot see. In Settings, Tracking, set "Visit buffering" and "Visitor storage" to "Database". The optimized endpoint works with files on a single server only and switches itself off otherwise.

= Does the plugin work behind a CDN or proxy? =

Yes. Visits are sent by the browser, so page caches do not matter. Set the client IP header (for example `CF-Connecting-IP`) in Settings, Tracking so excluded IPs and countries use the real address; Settings shows a hint when it detects a proxy.

= Which data leaves my server? =

None about visitors. Only the optional downloads of a country database (see External services) and the emails you switch on.

= How do traffic channels work? =

The first automatic pageview of a visit is an entrance and is assigned a channel from the referrer, utm_ tags and advertising click identifiers (only which ones were present is recorded, never their values). Later pageviews in the same tab keep that channel through the browser's session storage (key `d_analytics_src`, cleared when the tab closes). The share column is the share of entrances. Visits whose source cannot be known (for example a new tab opened from a link inside the site, or blocked storage) are left out rather than shown as Direct. Channel statistics start when you update to 1.1.0 and are not back-filled; after updating, purge page caches and the CDN, because cached pages still load the old tracker. A replacing import deletes the channel rows of the imported days, since imports carry no channel data. Developers can change the rules with the filters `d_analytics_channel_rules` and `d_analytics_channel_sources`.

= Does it work with the iPOS cookie banner or another Google Consent Mode v2 banner? =

Yes. The tracker reads `gtag( 'consent', 'default' | 'update', { analytics_storage } )` from `window.dataLayer`, so a banner that emits Consent Mode needs no snippet. If a page cache or script optimizer hides those calls, call `dAnalytics.setConsent( true | false )` from the banner's choice handler. A consent manager that lives only inside a Google Tag Manager template is not detected.

= How do I remove everything? =

Delete the plugin in wp-admin. Uninstalling removes its tables, options, user settings, files, scheduled jobs and capabilities. Settings, Data lets you export or reset the statistics first.

== External services ==

Visitor countries (Settings, Tracking) can come from a country database that the plugin downloads, once a week at most, with the WordPress HTTP API:

* DB-IP Lite country database (default). Fetched from download.db-ip.com, with the published checksum read from db-ip.com. Only the plugin version is sent in the user agent; no visitor data and no site address leave the site. The database is licensed CC BY 4.0, which is why the dashboard links to DB-IP under the Countries card. Service: https://db-ip.com. Terms: https://db-ip.com/terms. Privacy policy: https://db-ip.com/privacy
* MaxMind GeoLite2 Country (optional). Fetched from download.maxmind.com with your own account ID and licence key, which are sent only to MaxMind. Service: https://www.maxmind.com. Terms (GeoLite end user licence agreement): https://www.maxmind.com/en/geolite2/eula. Privacy policy: https://www.maxmind.com/en/privacy-policy

Lookups happen on your server. The visitor address is never stored. Choose "Off" or "Country header of a CDN" to download nothing. After the first successful download from DB-IP an administrator sees a one-time notice saying so, with a link to switch it off. A failed download is retried after 1 hour, then 2, 4 and so on, at most once a day.

== Privacy ==

Suggested privacy policy text is added to Settings, Privacy, Policy Guide. In short: no cookies and no stored IP addresses without consent; the country comes from an in-memory lookup of the visitor address (also before consent) and only the two-letter country is saved.

== Third-party software and data ==

* MaxMind DB Reader (maxmind-db/reader), Apache-2.0. Bundled with a prefixed namespace (DAnalytics\Vendor) generated by Strauss and no other change; its licence file is kept next to it.
* Country names: Unicode CLDR, Unicode License v3 (https://www.unicode.org/license.txt), with a few Vietnamese names corrected by hand.
* DB-IP Lite and MaxMind GeoLite2 data are downloaded, not bundled (see External services).

== Changelog ==

= 1.1.0 - 2026-10-21 =
* Added: Traffic channels (GA4-compatible names) with entrances, visitors, pageviews and share of entrances; a dashboard card, a section in the email reports, REST `GET d-analytics/v1/channels` and `wp d-analytics report channels`. Vietnamese services and AI assistants are recognised; advertising click identifiers are recorded as flags only.
* Added: Google Consent Mode v2 adapter (`analytics_storage` from `window.dataLayer`); the newest explicit signal wins over the WP Consent API.
* Added: filters `d_analytics_channel_rules` and `d_analytics_channel_sources`.
* Changed: `wp d-analytics report` accepts the action `channels`; `--period` is needed only for `send`.
* Changed: the tracker keeps the traffic source of the current tab in session storage (`d_analytics_src`); the suggested privacy text and the consent settings text describe it.
* Database: migration 2 adds `dimension_stats.entrances`. Channel statistics start after the update (no back-fill). Purge page caches after updating.

= 1.0.0 - 2026-10-20 =
First release. A port of Koko Analytics with these additions:

* Cookieless daily-hash uniqueness, consent-aware tracking (WP Consent API, `dAnalytics.setConsent()`), a strict pageview-only mode and a database fallback for buffering and visitor storage.
* Server-rendered dashboard with a WordPress dashboard widget, a pageviews column in the post list, an admin bar sparkline and a browser opt-out.
* Blocks, shortcodes, a widget, AMP support and WP-CLI commands.
* Importers for Koko Analytics, Plausible, Burst Statistics, WP Statistics, Independent Analytics, Statify and SlimStat.
* Vietnamese translation and Vietnamese referrer rules (Cốc Cốc, Zalo, TikTok, YouTube, Messenger, Gmail).
* Browsers, operating systems, devices and campaign (UTM) cards; only broad families are stored, never a version, model or raw user agent.
* Countries from a CDN header, the DB-IP Lite database (default) or MaxMind GeoLite2. Only the two-letter country is stored.
* Custom events: `dAnalytics.trackEvent()`, outbound link and form submission events, with daily caps per name and parameter.
* Optional weekly and monthly email reports and traffic spike alerts, with `wp d-analytics report send`.
* Developers: filter `d_analytics_endpoint_constants` bakes settings into the optimized endpoint; filter `d_analytics_importers` adds an importer.
