preflow / analytics
Preflow analytics — visits, page views, AI agents and bots counted on the server, with no cookie and no stored IP
Requires
- php: >=8.4
- matomo/device-detector: ^6.4
- preflow/core: ^0.98.0 || @dev
- preflow/data: ^0.98.0 || @dev
- preflow/devtools: ^0.98.0 || @dev
- preflow/routing: ^0.59 || @dev
Requires (Dev)
- phpunit/phpunit: ^11.0
Suggests
- preflow/auth: Leaves out signed-in staff who hold analytics.view (and everyone signed in with exclude_signed_in) and serves the stats over REST
Provides
None
Conflicts
- preflow/core: <0.98.0
- preflow/data: <0.98.0
- preflow/devtools: <0.98.0
- preflow/routing: <0.59
Replaces
None
This package is not auto-updated.
Last update: 2026-12-01 01:39:03 UTC
README
Counts the visits to your site on the server, so you can answer "how many people came, and what did the machines read?" without a cookie, a script in the page or a stored IP address.
The problem it solves
Most site statistics are wrong in two ways.
- They count machines as people. Search engines, monitors, scanners and AI crawlers all ask for pages. Counted as visitors, they make a quiet site look busy.
- They watch people to do it. A cookie or a script in the page follows a visitor around, and a log of raw IP addresses is personal data you now have to guard.
preflow/analytics counts on the server, from the request the site already answered. Each
request is put into one of four classes, so a person is not mixed up with a crawler. It stores
no raw IP, sets no cookie and starts no session.
Analytics is off by default. Off, the package binds a store that keeps nothing and runs nothing per request.
What it never stores
- The IP address. It is used for two things, in memory, after the response has gone out: to make the visitor hash and to look up the network it belongs to. Then it is dropped. It is not in a row, a log line or the debug toolbar. A failure is logged by its class name only, because a driver's message could quote the address.
- A cookie or a session. Nothing is set or started. (To leave out signed-in staff, the staff check reads a session the site already has.)
A visitor is this hash, in words: the first 32 hex characters of an HMAC-SHA256 of the client's network and the user agent, keyed with the day's random salt and the site URL. The "network" is an IPv4 address as it is, or an IPv6 address by its /64 prefix. The salt is made on the day's first request and kept only for that day. When the day is final its salt is deleted, so nobody, you included, can work out which hash an address and user agent would have made. A hash cannot be linked to a person or to another day.
What is stored per request: the day, the time, the page (host, path, the allowed query
parameters), the kind, the visitor hash, the class and its signals, the user agent, a referrer
from another site (host and path), the network's name and number (ASN), and the browser, system
and device the user agent names. Raw request rows are deleted after retention_days.
Install
In this order:
-
composer require preflow/analytics -
Add
Preflow\Analytics\AnalyticsServiceProvidertoconfig/providers.php. -
Turn it on in
config/analytics.php:return [ 'enabled' => true, ];
-
php preflow migrate
Turn it on before you migrate: the step that creates the analytics_* tables
(analytics.tables) is registered only while analytics is on. A request never creates a table.
Until you have migrated, requests are not counted and one warning says so.
-
The cron line is the one the site already has for
preflow/devtools.pages:workalso runs the analytics background work (see "Days"):* * * * * cd /path/to/site/current && php preflow pages:work >/dev/null 2>&1
Storage
By default the rows live in an SQLite file of their own, storage/analytics/analytics.sqlite,
so a site on JSON storage works too. To keep them in a site storage that runs SQL (SQLite or
MySQL), name it:
'storage' => 'mysql',
A name that is not a storage of config/data.php running SQL fails at boot, naming it.
The store is the interface Preflow\Analytics\Store\AnalyticsStore; SqlAnalyticsStore is its
SQL implementation and NullAnalyticsStore the one used while analytics is off.
What is counted
Each request the site answers is looked at once, whoever answered it: a page, the page cache, a
Markdown view or /llms.txt. The work runs after the response has gone out, so a visitor never
waits for it, and if it fails the page is unchanged (one warning is logged).
What it costs: the user agent is read by DeviceDetector, whose rules are YAML that takes about
0.3 s of CPU to parse. The parsed rules are kept as PHP files in storage/analytics/cache
(written on the first counted request; opcache keeps them compiled), so a fresh PHP process
classes a request in about 40 to 60 ms instead.
- Counted: a
GETanswered200with HTML (html), Markdown (markdown),/llms.txtor/llms-full.txt(llms), or an RSS, Atom or JSON feed (feed). AGETanswered404with HTML is counted asnot_found, apart from page views. - Not counted: other methods, the admin and other non-public paths, the API prefixes, editor
previews,
exclude_paths(a prefix covers whole path segments:/interncovers/intern/x, not/internal), and signed-in staff who holdanalytics.view(everyone signed in withexclude_signed_in). Staff are only recognised withpreflow/auth; without it nobody is left out. - Of the query string only
utm_source,utm_medium,utm_campaign,utm_content,utm_term,refandquery_allowlistare kept. A referrer is kept as host and path, and only when it is another site.
The four classes
Each request gets one class, the first match winning. The reasons are kept with the request as
short signals (ai:GPTBot, dd:Googlebot, hdr:no-lang, ...), so a day can be classed again.
| Class | Means | Examples |
|---|---|---|
ai |
A declared AI agent: the user agent names itself as an AI crawler, or as an AI assistant fetching a page for a user. | GPTBot, ClaudeBot, PerplexityBot |
bot |
A client that names itself as a bot or tool: a search engine, a monitor, an SEO tool, an automated browser, a chat link preview, an empty user agent. | Googlebot, an uptime monitor, HeadlessChrome |
suspected |
Not declared, but unlikely to be a person: an outdated or forged browser, a request from a datacenter network, a missing Accept or Accept-Language, an HTTP library, a very short user agent. |
an old IE user agent, a browser request from a cloud provider |
visitor |
Everything else. | a browser |
Only what a client says about itself makes it ai or bot. A browser that looks outdated or
forged, and a request from a datacenter, never say who they are, so they are suspected, not
bot. The "declared" in "declared AI agent" is the point: the package counts the agents that
say who they are, and does not claim to find the ones that do not.
Add agents the shipped list does not know with ai_agents, and network names with
datacenter_names.
Days
A day is the date in the analytics timezone. Its totals grow as requests come in. Two hours
after the day ends, pages:work finalises it: the totals are rebuilt from the raw rows, the day
is marked final and its salt is deleted. pages:work also deletes raw rows older than
retention_days, but never those of a day that is still open.
A day is provisional while its numbers may still change. A day without any hit is final once its end plus 2 hours has passed. A date in the future comes back as a provisional day of zeros.
Networks, re-scoring and pruning
preflow analytics:listsdownloads the network lists intolists_dirand imports them: DB-IP's free ASN list (monthly) and the AWS, Google Cloud, Oracle and DigitalOcean ranges. A network is a datacenter when it comes from a cloud list or its name matches a datacenter name (the shipped list plusdatacenter_names). A source that fails keeps its last import. Run it monthly, at a quiet hour: each source is imported in one transaction, and on the default SQLite file a request counted during the import cannot write (it is not counted, and one warning is logged).preflow analytics:rescore <from> [<to>](days asYYYY-MM-DD) classes the raw rows of those days again with the current lists and rules, then rebuilds their totals. A final day stays final. If any day of the range has lost its raw rows to pruning, nothing is re-scored and the command names the days. The IP is never stored, so a row keeps the network it had: it becomes a datacenter only when its stored network name matches a datacenter name now.preflow analytics:prunedeletes old raw rows now, by the same rule aspages:work.
Configuration
Every key, with its default:
| Key | Default | |
|---|---|---|
enabled |
false |
Count requests. |
storage |
'analytics' |
The storage, see above. |
retention_days |
30 |
How long raw request rows are kept, for re-scoring. Day totals are kept. |
exclude_paths |
[] |
Path prefixes that are never counted. |
exclude_signed_in |
false |
Leave out everyone signed in, not only staff with analytics.view. |
query_allowlist |
[] |
Query parameters kept besides utm_* and ref. |
timezone |
null |
The timezone days are counted in; null takes the app's. |
lists_dir |
'storage/analytics/lists' |
Where downloaded network lists are kept. |
ai_agents |
[] |
More AI agent tokens: 'Token' => ['family' => 'Name', 'kind' => 'crawler'] (or 'user'). |
datacenter_names |
[] |
More network names that mark a datacenter. |
Reading the stats in PHP
Preflow\Analytics\AnalyticsReader is bound whether analytics is on or not (off, it reads
nothing and answers zeros). Dates are Y-m-d in the analytics timezone, both ends included, at
most 366 days at once. A bad date, a range over 366 days, an unknown class or a limit out of
bounds throws \InvalidArgumentException with the reason.
$reader = $container->get(AnalyticsReader::class); [$from, $to] = $reader->range(null, null); // the last 30 days, ending today $summary = $reader->summary($from, $to); // totals, previous period, note $days = $reader->timeline($from, $to); // one entry per day $pages = $reader->topPages($from, $to, 'visitor'); // class, family, limit, offset $agents = $reader->aiAgents($from, $to); $bots = $reader->bots($from, $to); $missing = $reader->notFound($from, $to);
What to know about the numbers:
- Visitors are per day. A period's visitors are the sum of its days' visitors, so every
answer with a period's visitors carries
visitors_counted_per_day: trueand this note:A person who comes back on another day counts again. summary()gives totals per class (visitors,visits,page_views) plusnot_found, and the same for the previous period of equal length directly before.not_foundcounts visitors only: a scan by a bot does not bury the broken links people hit.provisional_dayslists the days of the period and of the previous period that may still change.- A day without hits is zeros. A date in the future is a provisional day of zeros.
Reading the stats over REST
Routes are registered when analytics is on, the site has an API prefix (config/api.php,
/api by default) and preflow/auth is set up with config/auth.php. Without an API prefix
or without configured auth there are no routes at all; the PHP reader above works regardless.
All routes are GET, under the first API prefix. They take from and to (Y-m-d; by default
the last 30 days ending today).
| Route | Answers | Extra query |
|---|---|---|
/api/analytics/summary |
totals, previous period, provisional_days |
|
/api/analytics/timeline |
one entry per day | |
/api/analytics/pages |
the pages a class viewed most | class (visitor), family, limit (10), offset (0) |
/api/analytics/ai |
declared AI agents by family and kind | |
/api/analytics/bots |
known bots | limit (20) |
/api/analytics/not-found |
pages that answered not found to visitors | limit (20) |
The list routes (timeline, pages, ai, bots, not-found) carry the period in meta;
pages and not-found also carry visitors_counted_per_day and the note. summary has them in
its data. A bad query answers 422 with the reason; a limit is 1 to 100.
Nobody signed in gets 401, whatever the auth config says: the stats are never public. Someone
signed in without analytics.view gets 403.
Using the reader in GraphQL
A resolver is a plain call to the reader. With any GraphQL library, a field resolves like this:
$container is the app's container ($app->container()), and $access is
Preflow\Auth\Access\Access from it ($container->get(Access::class)), which exists only with
preflow/auth:
'analyticsTopPages' => static function (array $args) use ($container, $access): array { if (!$access->can('analytics.view')) { throw new \RuntimeException('Not allowed.'); } $reader = $container->get(AnalyticsReader::class); [$from, $to] = $reader->range($args['from'] ?? null, $args['to'] ?? null); return $reader->topPages($from, $to, $args['class'] ?? 'visitor', null, $args['limit'] ?? 10); },
The reader does not check who asks: the resolver does, as above.
Permissions
analytics.view reads the stats: the REST routes check it, and a GraphQL resolver checks it
itself (see above). analytics.manage is declared for the re-score and list actions, for an
admin screen that offers them; the CLI commands (analytics:rescore, analytics:lists,
analytics:prune) check no permission, as whoever runs them already has the server. Both are
declared in the group "Analytics" when preflow/auth is installed. With the default access
resolver every staff user holds analytics.view.
What you don't have to do
For an ordinary site you write no code: turn it on, migrate, keep the cron line. The observer, the hashing, the classes, finalising days and pruning all happen by themselves.
One sentence to remember
Analytics counts each request once, on the server, as a person, a bot, a declared AI agent or something suspicious, and keeps no address, cookie or session that could follow anyone.
Credits and licence
MIT.
IP data by DB-IP: the DB-IP Lite ASN list, licensed CC BY 4.0. It is
downloaded by analytics:lists, not shipped.
User agents are read with matomo/device-detector (LGPL-3.0).