diff --git a/CHANGELOG.md b/CHANGELOG.md index cb82ae4..c2ee792 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ the section is the text of the release in Gitea. address and the browser. Modules name their routes with the new `actions()` and `views()`. - Address bans: by hand, for a group of addresses, or by itself after too many failed logins; optionally for the whole app. `manager:unban` and `manager:audit-prune`. +- Statistics (module `statistics`, off by default): page views and time on a page without cookies or stored addresses, sources, + devices, programs, comparisons and CSV export. Which pages count is up to the site. - Breaking for a module that implements `Contract\Module` without extending `BaseModule`: the contract gained `actions()`, `views()` and `middleware()`. - `CLAUDE.md` and the rules shared with the other IriksIT repos in `AGENTS.md`. diff --git a/README.md b/README.md index edc8d1e..4f228d4 100644 --- a/README.md +++ b/README.md @@ -21,9 +21,10 @@ Put `IriksIT\Manager\Concerns\HasManagerAccess` on the `User` model. The manager | `posts` | Posts | on | | `reviews` | Reviews | off | | `audit` | Audit log and address bans | off | +| `statistics` | Visitor statistics | off | Switch a part in `config/manager.php` (`modules`) or with `MANAGER_PAGES`, `MANAGER_POSTS`, -`MANAGER_REVIEWS`, `MANAGER_AUDIT`. A module that is off has **no routes, no tables, no menu item and no permissions**: +`MANAGER_REVIEWS`, `MANAGER_AUDIT`, `MANAGER_STATISTICS`. A module that is off has **no routes, no tables, no menu item and no permissions**: its migrations are not loaded at all. A module that needs another one (`requires()`) fails at boot when that one is off. @@ -106,14 +107,32 @@ privacy policy (`MANAGER_AUDIT=true`). `max_keep_days` (`MANAGER_AUDIT_MAX_KEEP_DAYS`, 90): the longest the log may be kept, which your privacy policy has to agree with. `manager:audit-prune` runs daily and deletes old lines and ended bans; notes stay until removed. +## Statistics module + +Off by default (`MANAGER_STATISTICS=true`). The site's own visitor statistics, with no cookie and no stored IP address: +a visitor is a code made of the address, the browser and a random key that is deleted after a day (`manager:forget-visitor-keys`, +scheduled daily), so a code cannot be traced back afterwards. A browser that sends `DNT` or `Sec-GPC` is not counted. + +- **Reporting**: the pages of your site `POST` to `/pulse/view` (`{path, referrer, via, campaign}`, answers `{token}`) and, when the + visitor leaves, `/pulse/leave` (`{token, seconds}`). No session, rate limited (`manager.statistics.per_minute`). +- **Which pages count**: only addresses you name, so nobody can fill the statistics with made-up ones: + `manager.statistics.pages`, the posts under `manager.statistics.posts_path` (published ones only), and anything else through + `app(IriksIT\Manager\Modules\Statistics\CountedPages::class)->register(fn (string $path) => ...)`. +- **Programs**: the pages served to search engines, crawlers and previews are counted per day, program and page (no address, no browser + line), by a middleware the module adds to the `web` group (`manager.statistics.count_bots`). +- **The report** (`statistics.view`): visitors, visits, page views, time, bounce rate, a comparison with another period, pages, posts, + sources and channels, devices, heatmap, programs; `GET /manager/statistics?range=30d` and a CSV per sheet + (`/manager/statistics/export?sheet=days|pages|sources|bots`). +- **Country** only when `manager.statistics.country_header` names a header (Cloudflare: `CF-IPCountry`). + ## State of this version Done: module registry and switches, permissions per module, users (accounts, groups, command), media -(library and public file route) posts (with categories and tags) and the audit log with bans, 83 tests (`composer test`). +(library and public file route) posts (with categories and tags) and the audit log with bans and the statistics, 99 tests (`composer test`). The answers of every action are JSON, in the shape the screens of bouwbedrijf.iriks-it.nl got as Inertia props. The screens themselves are not in the package yet: the frontend is an open decision -(`AGENTS.md`). Pages and reviews are still skeletons (a list), and login, profile, statistics and revisions are not +(`AGENTS.md`). Pages and reviews are still skeletons (a list), and login, profile and revisions are not ported yet. ## Development cycle diff --git a/TOKENS.md b/TOKENS.md index 2bbbff3..96b773b 100644 --- a/TOKENS.md +++ b/TOKENS.md @@ -14,3 +14,4 @@ Per stuk werk een rij; zie `dev/token-usage.py`. | 2026-12-04 | De changelog van de eerste release hersteld, de kop stond verkeerd | - | claude-sonnet-5-5 | 5 | 3.535 | 10 | 6.917 | 1.656.465 | 0,03 | | 2026-12-04 | Composer-cache en herhaalpogingen in alle CI-jobs, zodat haperende downloads de pipeline niet meer breken | - | claude-sonnet-5-5 | 74 | 80.637 | 164 | 167.489 | 21.208.458 | 0,65 | | 2026-12-04 | Auditlog en banbeheer als module 'audit' overgenomen uit bouwbedrijf, met tests, en de gedeelde regels van de andere repo's in AGENTS.md | - | claude-sonnet-5-5 | 38 | 49.634 | 82 | 92.591 | 5.342.800 | 0,18 | +| 2026-12-04 | Bezoekersstatistieken als module 'statistics' overgenomen uit bouwbedrijf: paginaweergaven zonder cookies, bronnen, bots en export | - | claude-sonnet-5-5 | 12 | 16.807 | 24 | 20.717 | 2.545.198 | 0,03 | diff --git a/config/manager.php b/config/manager.php index d1db7b4..e2351e0 100644 --- a/config/manager.php +++ b/config/manager.php @@ -30,6 +30,7 @@ return [ Modules\Posts\PostsModule::class, Modules\Reviews\ReviewsModule::class, Modules\Audit\AuditModule::class, + Modules\Statistics\StatisticsModule::class, ], /* @@ -44,6 +45,7 @@ return [ 'posts' => env('MANAGER_POSTS', true), 'reviews' => env('MANAGER_REVIEWS', false), 'audit' => env('MANAGER_AUDIT', false), + 'statistics' => env('MANAGER_STATISTICS', false), ], /* @@ -97,6 +99,31 @@ return [ 'whole_site_bans' => (bool) env('MANAGER_AUDIT_WHOLE_SITE_BANS', false), ], + /* + | The visitor statistics (module `statistics`). + */ + 'statistics' => [ + // The addresses of the public site that count as a page. Anything else is ignored, so + // nobody can fill the statistics with made-up addresses. Posts and other kinds of pages + // come from `posts_path` or a resolver: app(CountedPages::class)->register(fn ($path) => ...). + 'pages' => ['/'], + + // The address under which the posts live (`/blog` for `/blog/my-post`); null: posts are not counted. + 'posts_path' => null, + + // Where the public pages report a view (POST {pulse_path}/view and {pulse_path}/leave). + 'pulse_path' => 'pulse', + + // Reports per minute per address. + 'per_minute' => 120, + + // The request header with the country code of the visitor, e.g. CF-IPCountry behind Cloudflare. Null: no country. + 'country_header' => env('MANAGER_STATISTICS_COUNTRY_HEADER'), + + // Count the pages served to programs (search engines, crawlers) by adding a middleware to the `web` group. + 'count_bots' => (bool) env('MANAGER_STATISTICS_COUNT_BOTS', true), + ], + /* | Prefix for the tables of the package. */ diff --git a/src/Models/PageView.php b/src/Models/PageView.php new file mode 100644 index 0000000..8c485c4 --- /dev/null +++ b/src/Models/PageView.php @@ -0,0 +1,26 @@ + 'datetime', 'hour' => 'integer', 'seconds' => 'integer']; + } + + /** @return BelongsTo */ + public function visit(): BelongsTo + { + return $this->belongsTo(Visit::class); + } +} diff --git a/src/Models/Visit.php b/src/Models/Visit.php new file mode 100644 index 0000000..bdde6d7 --- /dev/null +++ b/src/Models/Visit.php @@ -0,0 +1,34 @@ + 'datetime', + 'last_seen_at' => 'datetime', + 'hour' => 'integer', + 'weekday' => 'integer', + 'page_views' => 'integer', + 'seconds' => 'integer', + ]; + } + + /** @return HasMany */ + public function pageViews(): HasMany + { + return $this->hasMany(PageView::class); + } +} diff --git a/src/Models/VisitorSalt.php b/src/Models/VisitorSalt.php new file mode 100644 index 0000000..de340f4 --- /dev/null +++ b/src/Models/VisitorSalt.php @@ -0,0 +1,52 @@ +toDateString(); + $salt = static::query()->where('day', $today)->value('salt'); + + if (is_string($salt)) { + return $salt; + } + + static::forgetOld(); + + try { + return static::query()->create(['day' => $today, 'salt' => Str::random(64)])->salt; + } catch (UniqueConstraintViolationException) { + // Another visitor arrived in the same instant and made today's key. + return static::query()->where('day', $today)->sole()->salt; + } + } + + /** Deletes every key that is not today's. Returns how many. */ + public static function forgetOld(): int + { + $deleted = static::query()->where('day', '<', now()->toDateString())->delete(); + + return is_int($deleted) ? $deleted : 0; + } +} diff --git a/src/Modules/Statistics/BotRecorder.php b/src/Modules/Statistics/BotRecorder.php new file mode 100644 index 0000000..ba95cb7 --- /dev/null +++ b/src/Modules/Statistics/BotRecorder.php @@ -0,0 +1,65 @@ +bot(); + + if ($bot === null) { + return; + } + + $day = now()->toDateString(); + $name = $bot['name'] ?? self::OTHER; + + if ($bot['kind'] === 'other' && $name !== self::OTHER && $this->isOneTooMany($table, $day, $name)) { + $name = self::OTHER; + } + + // One statement, so two requests at the same moment both count. + DB::table($table)->upsert( + [['day' => $day, 'bot' => $name, 'kind' => $bot['kind'], 'path' => Str::limit('/'.trim(Str::before($path, '?'), '/'), 255, ''), 'hits' => 1]], + ['day', 'bot', 'path'], + ['hits' => DB::raw($table.'.hits + 1')], + ); + } + + private function isOneTooMany(string $table, string $day, string $name): bool + { + $unknown = DB::table($table)->where('day', $day)->where('kind', 'other'); + + if ((clone $unknown)->where('bot', $name)->exists()) { + return false; + } + + return $unknown->distinct()->count('bot') >= self::UNKNOWN_NAMES_A_DAY; + } +} diff --git a/src/Modules/Statistics/CountBots.php b/src/Modules/Statistics/CountBots.php new file mode 100644 index 0000000..fdcb51e --- /dev/null +++ b/src/Modules/Statistics/CountBots.php @@ -0,0 +1,50 @@ +counts($request, $response)) { + try { + $this->recorder->hit((string) $request->userAgent(), $request->getPathInfo()); + } catch (Throwable $e) { + // Counting must never be the reason a page is not served. + report($e); + } + } + + return $response; + } + + private function counts(Request $request, Response $response): bool + { + $name = $request->route()?->getName(); + + return $request->isMethod('GET') + && $response->getStatusCode() === 200 + && is_string($name) + && ! str_starts_with($name, 'manager.') + // The same promise as for visitors: who asks not to be followed is not counted at all. + && $request->header('Sec-GPC') !== '1' + && $request->header('DNT') !== '1'; + } +} diff --git a/src/Modules/Statistics/CountedPages.php b/src/Modules/Statistics/CountedPages.php new file mode 100644 index 0000000..c546a50 --- /dev/null +++ b/src/Modules/Statistics/CountedPages.php @@ -0,0 +1,59 @@ + */ + private array $resolvers = []; + + /** + * @param Closure(string): (array{path: string, post_id: int|null}|null) $resolver gets a path like `/about`, returns the page or null + */ + public function register(Closure $resolver): void + { + $this->resolvers[] = $resolver; + } + + /** @return array{path: string, post_id: int|null}|null */ + public function resolve(string $path): ?array + { + $pages = array_map(fn (string $page) => '/'.trim($page, '/'), (array) config('manager.statistics.pages', ['/'])); + + if (in_array($path, $pages, true)) { + return ['path' => $path, 'post_id' => null]; + } + + $postsPath = config('manager.statistics.posts_path'); + + if (is_string($postsPath) && $postsPath !== '' && Manager::enabled('posts')) { + $prefix = '/'.trim($postsPath, '/').'/'; + + if (str_starts_with($path, $prefix)) { + $post = Post::query()->published()->where('slug', substr($path, strlen($prefix)))->first(); + + return $post instanceof Post ? ['path' => $path, 'post_id' => $post->id] : null; + } + } + + foreach ($this->resolvers as $resolver) { + $page = $resolver($path); + + if ($page !== null) { + return $page; + } + } + + return null; + } +} diff --git a/src/Modules/Statistics/ForgetVisitorKeys.php b/src/Modules/Statistics/ForgetVisitorKeys.php new file mode 100644 index 0000000..a68a275 --- /dev/null +++ b/src/Modules/Statistics/ForgetVisitorKeys.php @@ -0,0 +1,20 @@ +line(sprintf('%d key(s) of past days deleted.', VisitorSalt::forgetOld())); + + return self::SUCCESS; + } +} diff --git a/src/Modules/Statistics/PulseController.php b/src/Modules/Statistics/PulseController.php new file mode 100644 index 0000000..2c1984c --- /dev/null +++ b/src/Modules/Statistics/PulseController.php @@ -0,0 +1,47 @@ +header('Sec-GPC') === '1' || $request->header('DNT') === '1') { + return response()->json(['token' => null])->header('Cache-Control', 'no-store'); + } + + $countryHeader = config('manager.statistics.country_header'); + + $token = $recorder->view( + (string) $request->ip(), + (string) $request->userAgent(), + $request->string('path')->limit(300, '')->toString(), + [ + 'via' => $request->string('via')->limit(40, '')->toString(), + 'campaign' => $request->string('campaign')->limit(80, '')->toString(), + 'referrer' => $request->string('referrer')->limit(2000, '')->toString(), + // Only the country code is kept, and only when the site names the header that has it (Cloudflare: CF-IPCountry). + 'country' => is_string($countryHeader) && $countryHeader !== '' ? (string) $request->header($countryHeader, '') : '', + 'host' => $request->getHost(), + ], + ); + + return response()->json(['token' => $token])->header('Cache-Control', 'no-store'); + } + + public function leave(Request $request, VisitRecorder $recorder): Response + { + $recorder->leave($request->string('token')->limit(40, '')->toString(), $request->integer('seconds')); + + return response()->noContent()->header('Cache-Control', 'no-store'); + } +} diff --git a/src/Modules/Statistics/Source.php b/src/Modules/Statistics/Source.php new file mode 100644 index 0000000..b860bb7 --- /dev/null +++ b/src/Modules/Statistics/Source.php @@ -0,0 +1,122 @@ +, which + * is what tells a click on my own post apart from someone else's link. + */ +final class Source +{ + /** The platforms the site shares posts to; the values of ?via=. */ + public const PLATFORMS = ['linkedin', 'x', 'facebook', 'instagram']; + + /** Host (or the end of one) => platform. */ + private const SOCIAL = [ + 'linkedin.com' => 'linkedin', 'lnkd.in' => 'linkedin', 'com.linkedin.android' => 'linkedin', + 't.co' => 'x', 'x.com' => 'x', 'twitter.com' => 'x', 'com.twitter.android' => 'x', + 'facebook.com' => 'facebook', 'fb.com' => 'facebook', 'fb.me' => 'facebook', 'com.facebook.katana' => 'facebook', + 'instagram.com' => 'instagram', 'com.instagram.android' => 'instagram', + 'threads.net' => 'threads', 'threads.com' => 'threads', 'bsky.app' => 'bluesky', 'reddit.com' => 'reddit', + 'youtube.com' => 'youtube', 'youtu.be' => 'youtube', 'news.ycombinator.com' => 'hackernews', + 'tweakers.net' => 'tweakers', + ]; + + /** Host (or the end of one) => search engine. */ + private const SEARCH = [ + 'bing.com' => 'bing', 'duckduckgo.com' => 'duckduckgo', 'ecosia.org' => 'ecosia', + 'startpage.com' => 'startpage', 'search.brave.com' => 'brave', 'yandex.com' => 'yandex', 'yandex.ru' => 'yandex', + 'baidu.com' => 'baidu', 'kagi.com' => 'kagi', 'qwant.com' => 'qwant', 'search.yahoo.com' => 'yahoo', + 'com.google.android.googlequicksearchbox' => 'google', + ]; + + private function __construct( + public readonly string $channel, + public readonly ?string $source, + public readonly ?string $referrerHost, + ) {} + + /** + * @param string $via the ?via= of the address the visitor arrived on + * @param string $campaign its ?utm_source= + * @param string $referrer the address of the page that linked here + * @param string $ownHost this site's own host: a link from the site itself is no source + */ + public static function of(string $via, string $campaign, string $referrer, string $ownHost): self + { + $host = self::host($referrer); + if ($host === self::bare($ownHost)) { + $host = null; + } + + $via = strtolower(trim($via)); + if (in_array($via, self::PLATFORMS, true)) { + return new self('share', $via, $host); + } + + $campaign = strtolower(trim($campaign)); + if ($campaign !== '' && preg_match('/^[a-z0-9._-]{1,80}$/', $campaign) === 1) { + $platform = self::SOCIAL[$campaign.'.com'] ?? ($campaign === 'twitter' ? 'x' : null); + + return $platform !== null ? new self('social', $platform, $host) : new self('campaign', $campaign, $host); + } + + if ($host === null) { + return new self('direct', null, null); + } + + if (($platform = self::match($host, self::SOCIAL)) !== null) { + return new self('social', $platform, $host); + } + + // google.com, google.nl, google.co.uk ... + if (preg_match('/(^|\.)google\.[a-z.]{2,6}$/', $host) === 1) { + return new self('search', 'google', $host); + } + + if (($engine = self::match($host, self::SEARCH)) !== null) { + return new self('search', $engine, $host); + } + + return new self('referral', $host, $host); + } + + /** The host of an address, lower case and without "www."; null when there is none. */ + private static function host(string $address): ?string + { + $address = trim($address); + if ($address === '') { + return null; + } + + $host = parse_url($address, PHP_URL_HOST); + if (! is_string($host) || $host === '' || strlen($host) > 255) { + return null; + } + + return self::bare($host); + } + + private static function bare(string $host): string + { + $host = strtolower($host); + + return str_starts_with($host, 'www.') ? substr($host, 4) : $host; + } + + /** @param array $known */ + private static function match(string $host, array $known): ?string + { + foreach ($known as $end => $name) { + if ($host === $end || str_ends_with($host, '.'.$end)) { + return $name; + } + } + + return null; + } +} diff --git a/src/Modules/Statistics/Statistics.php b/src/Modules/Statistics/Statistics.php new file mode 100644 index 0000000..e05336b --- /dev/null +++ b/src/Modules/Statistics/Statistics.php @@ -0,0 +1,745 @@ + 'Today', 'week' => 'This week', '7d' => 'Last 7 days', 'month' => 'This month', '30d' => 'Last 30 days', + '12m' => 'Last 12 months', 'all' => 'All time', + ]; + + /** A period between two dates of one's own choosing (`from` and `to`). */ + public const CUSTOM = 'custom'; + + /** What a period can be put next to: the one before it, the same days a year earlier, days of one's own choosing, or nothing. */ + public const COMPARISONS = ['previous' => 'The period before', 'year' => 'A year earlier', 'custom' => 'Another period', 'none' => 'Nothing']; + + /** What can be downloaded as a CSV file. */ + public const EXPORTS = ['days' => 'Per day', 'pages' => 'Pages', 'sources' => 'Sources', 'bots' => 'Bots']; + + public const DEFAULT_RANGE = '30d'; + + private const WEEKDAYS = [1 => 'Mon', 2 => 'Tue', 3 => 'Wed', 4 => 'Thu', 5 => 'Fri', 6 => 'Sat', 7 => 'Sun']; + + /** + * Everything the statistics page shows for one period. + * + * @param array $choice `from` and `to` for a period of one's own, `compare` (see COMPARISONS) and `compare_from` + * @return array + */ + public function report(string $range, array $choice = []): array + { + $period = $this->period($range, $choice); + $from = $period['from']; + $to = $period['to']; + $compares = $period['previous_from'] !== null && $period['previous_to'] !== null; + + return [ + 'range' => [ + 'key' => $period['key'], + 'label' => $period['label'], + 'from' => $from, + 'to' => $to, + 'bucket' => $period['bucket'], + 'compare' => $period['compare'], + 'compared_to' => $period['compared_to'], + 'previous_from' => $period['previous_from'], + 'previous_to' => $period['previous_to'], + ], + 'ranges' => $this->ranges(), + 'comparisons' => self::COMPARISONS, + 'exports' => self::EXPORTS, + 'totals' => $this->totals($from, $to), + 'previous' => $compares ? $this->totals((string) $period['previous_from'], (string) $period['previous_to'], $period['previous_until_hour']) : null, + 'series' => $this->series($from, $to, $period['bucket']), + // The other period, step by step: the first step of it next to the first step of this one. + 'previous_series' => $compares ? $this->series((string) $period['previous_from'], (string) $period['previous_to'], $period['bucket']) : null, + 'pages' => $this->pages($from, $to), + 'posts' => $this->posts($from, $to), + 'channels' => $this->grouped($from, $to, 'channel', 10), + 'platforms' => $this->platforms($from, $to), + 'sources' => $this->sources($from, $to), + 'heatmap' => $this->heatmap($from, $to), + 'countries' => $this->grouped($from, $to, 'country', 8), + 'devices' => $this->grouped($from, $to, 'device', 5), + 'browsers' => $this->grouped($from, $to, 'browser', 6), + 'systems' => $this->grouped($from, $to, 'os', 6), + // Programs have no hour, so "today until now" has nothing fair to stand next to. + 'bots' => $this->bots($from, $to, $compares && $period['previous_until_hour'] === null ? [(string) $period['previous_from'], (string) $period['previous_to']] : null), + ]; + } + + /** + * The few numbers of a period that the screen of the owner shows (`OwnerNumbers`): the + * totals next to the period before, the visitors step by step, and the pages, articles + * and ways in that were used most. + * + * @return array{from: string, to: string, bucket: string, totals: array{visitors: int, visits: int, page_views: int, average_seconds: int, bounce_rate: int}, previous: array{visitors: int, visits: int, page_views: int, average_seconds: int, bounce_rate: int}|null, series: list, pages: list, posts: list, channels: list} + */ + public function brief(string $range): array + { + $period = $this->period($range); + $from = $period['from']; + $to = $period['to']; + + return [ + 'from' => $from, + 'to' => $to, + 'bucket' => $period['bucket'], + 'totals' => $this->totals($from, $to), + 'previous' => $period['previous_from'] !== null && $period['previous_to'] !== null + ? $this->totals($period['previous_from'], $period['previous_to'], $period['previous_until_hour']) + : null, + 'series' => $this->series($from, $to, $period['bucket']), + 'pages' => $this->pages($from, $to, 6), + 'posts' => $this->posts($from, $to), + 'channels' => $this->grouped($from, $to, 'channel', 6), + ]; + } + + /** + * One list of the period as rows for a CSV file. An unknown list gives the days. + * + * @param array $choice + * @return array{filename: string, header: list, rows: list>} + */ + public function export(string $sheet, string $range, array $choice = []): array + { + $period = $this->period($range, $choice); + $from = $period['from']; + $to = $period['to']; + $sheet = array_key_exists($sheet, self::EXPORTS) ? $sheet : 'days'; + + [$header, $rows] = match ($sheet) { + 'pages' => [['Page', 'Title', 'Views', 'Average seconds on the page'], array_map( + fn (array $page) => [$page['path'], $page['title'] ?? '', $page['views'], $page['average_seconds']], + $this->pages($from, $to, null), + )], + 'sources' => [['Source', 'Channel', 'Visits'], array_map( + fn (array $source) => [$source['name'], $source['channel'], $source['visits']], + $this->sources($from, $to, null), + )], + 'bots' => [['Program', 'Kind', 'Page', 'Requests'], $this->botRows($from, $to)], + default => [['Day', 'Visitors', 'Visits', 'Page views', 'Requests by programs'], array_map( + fn (array $day) => [$day['key'], $day['visitors'], $day['visits'], $day['page_views'], $day['bot_hits']], + $this->series($from, $to, 'day'), + )], + }; + + return ['filename' => "statistics-{$sheet}-{$from}-to-{$to}.csv", 'header' => $header, 'rows' => $rows]; + } + + /** + * The short version for the dashboard: today, the last 7 and the last 30 days, + * each next to the period before it, and the visitors per day of the last 30 days. + * + * @return array{periods: list, days: list} + */ + public function summary(): array + { + $periods = []; + + foreach (['today', '7d', '30d'] as $range) { + $period = $this->period($range); + $now = $this->totals($period['from'], $period['to']); + $before = $period['previous_from'] !== null && $period['previous_to'] !== null + ? $this->totals($period['previous_from'], $period['previous_to'], $period['previous_until_hour']) + : null; + + $periods[] = [ + 'key' => $range, + 'label' => $period['label'], + 'visitors' => $now['visitors'], + 'page_views' => $now['page_views'], + 'previous_visitors' => $before['visitors'] ?? 0, + ]; + } + + $month = $this->period('30d'); + + return ['periods' => $periods, 'days' => $this->series($month['from'], $month['to'], 'day')]; + } + + /** + * A period as dates, with the period it is compared with. An unknown key + * gives the default period. + * + * @param array $choice + * @return array{key: string, label: string, from: string, to: string, bucket: string, compare: string, compared_to: string|null, previous_from: string|null, previous_to: string|null, previous_until_hour: int|null} + */ + private function period(string $range, array $choice = []): array + { + $period = $this->dates($range, $choice); + $compare = $choice['compare'] ?? 'previous'; + $nothing = ['compare' => 'none', 'compared_to' => null, 'previous_from' => null, 'previous_to' => null, 'previous_until_hour' => null]; + + // All time has nothing before it. + if ($period['previous_from'] === null || $compare === 'none') { + return $nothing + $period; + } + + $from = CarbonImmutable::parse($period['from']); + $to = CarbonImmutable::parse($period['to']); + + if ($compare === 'year') { + return [ + 'compare' => 'year', 'compared_to' => 'the same days a year earlier', + 'previous_from' => $from->subYearNoOverflow()->toDateString(), 'previous_to' => $to->subYearNoOverflow()->toDateString(), + ] + $period; + } + + $start = $compare === 'custom' ? self::date($choice['compare_from'] ?? '') : null; + + if ($start !== null) { + // As many days as the period itself, from the chosen day on. + $end = $start->addDays((int) $from->diffInDays($to)); + + return [ + 'compare' => 'custom', 'compared_to' => self::span($start, $end), + 'previous_from' => $start->toDateString(), 'previous_to' => $end->toDateString(), + ] + $period; + } + + return ['compare' => 'previous'] + $period; + } + + /** + * The dates of a period, and of the period before it. + * + * @param array $choice + * @return array{key: string, label: string, from: string, to: string, bucket: string, compared_to: string|null, previous_from: string|null, previous_to: string|null, previous_until_hour: int|null} + */ + private function dates(string $range, array $choice): array + { + $today = CarbonImmutable::now()->startOfDay(); + $day = fn (CarbonImmutable $date): string => $date->toDateString(); + + if (preg_match('/^\d{4}$/', $range) === 1 && in_array((int) $range, $this->years(), true)) { + $start = $today->setDate((int) $range, 1, 1); + + return [ + 'key' => $range, 'label' => $range, 'from' => $day($start), 'to' => $day($start->endOfYear()), 'bucket' => 'month', + 'compared_to' => (string) ((int) $range - 1), + 'previous_from' => $day($start->subYear()), 'previous_to' => $day($start->subDay()), 'previous_until_hour' => null, + ]; + } + + $from = self::date($choice['from'] ?? ''); + $to = self::date($choice['to'] ?? ''); + + if ($range === self::CUSTOM && $from !== null && $to !== null) { + // The wrong way round, or into the future: still a period. + [$from, $to] = $from <= $to ? [$from, $to] : [$to, $from]; + $to = $to->min($today); + $from = $from->min($to); + $days = (int) $from->diffInDays($to) + 1; + + return [ + 'key' => self::CUSTOM, 'label' => self::span($from, $to), 'from' => $day($from), 'to' => $day($to), + 'bucket' => match (true) { + $days === 1 => 'hour', + $days <= 92 => 'day', + $days <= 1100 => 'month', + default => 'year', + }, + 'compared_to' => $days === 1 ? 'the day before' : "the {$days} days before", + 'previous_from' => $day($from->subDays($days)), 'previous_to' => $day($from->subDay()), 'previous_until_hour' => null, + ]; + } + + if (! array_key_exists($range, self::RANGES)) { + $range = self::DEFAULT_RANGE; + } + + $period = ['key' => $range, 'label' => self::RANGES[$range], 'to' => $day($today), 'previous_until_hour' => null]; + $monday = $today->startOfWeek(CarbonImmutable::MONDAY); + $lastMonth = $today->startOfMonth()->subMonthNoOverflow(); + + return match ($range) { + // Today so far, next to yesterday up to the same hour: a fair comparison at any time of day. + 'today' => ['previous_until_hour' => CarbonImmutable::now()->hour] + $period + [ + 'from' => $day($today), 'bucket' => 'hour', 'compared_to' => 'yesterday at this time', + 'previous_from' => $day($today->subDay()), 'previous_to' => $day($today->subDay()), + ], + // A week and a month that are still running stand next to as many days of the one before. + 'week' => $period + [ + 'from' => $day($monday), 'bucket' => 'day', 'compared_to' => 'last week up to the same day', + 'previous_from' => $day($monday->subWeek()), 'previous_to' => $day($today->subWeek()), + ], + 'month' => $period + [ + 'from' => $day($today->startOfMonth()), 'bucket' => 'day', 'compared_to' => 'last month up to the same day', + 'previous_from' => $day($lastMonth), 'previous_to' => $day($lastMonth->setDay(min($today->day, $lastMonth->daysInMonth))), + ], + '7d' => $period + [ + 'from' => $day($today->subDays(6)), 'bucket' => 'day', 'compared_to' => 'the 7 days before', + 'previous_from' => $day($today->subDays(13)), 'previous_to' => $day($today->subDays(7)), + ], + '12m' => $period + [ + 'from' => $day($today->startOfMonth()->subMonthsNoOverflow(11)), 'bucket' => 'month', 'compared_to' => 'the 12 months before', + 'previous_from' => $day($today->startOfMonth()->subMonthsNoOverflow(23)), + 'previous_to' => $day($today->startOfMonth()->subMonthsNoOverflow(11)->subDay()), + ], + 'all' => $period + [ + 'from' => $this->firstDay() ?? $day($today), + // Months while that still fits on the screen, years after that. + 'bucket' => CarbonImmutable::parse($this->firstDay() ?? $day($today))->diffInMonths($today) > 24 ? 'year' : 'month', + 'compared_to' => null, 'previous_from' => null, 'previous_to' => null, + ], + default => $period + [ + 'from' => $day($today->subDays(29)), 'bucket' => 'day', 'compared_to' => 'the 30 days before', + 'previous_from' => $day($today->subDays(59)), 'previous_to' => $day($today->subDays(30)), + ], + }; + } + + /** A date as 'Y-m-d' from the address bar, or null when it is not one. */ + private static function date(string $value): ?CarbonImmutable + { + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value) !== 1) { + return null; + } + + $date = CarbonImmutable::createFromFormat('!Y-m-d', $value); + + // "2026-02-31" is read as the 3rd of March: not what was typed, so not a date. + return $date instanceof CarbonImmutable && $date->toDateString() === $value && $date->year >= 2000 ? $date : null; + } + + /** "1 Oct – 31 Oct 2026" */ + private static function span(CarbonImmutable $from, CarbonImmutable $to): string + { + if ($from->equalTo($to)) { + return $from->format('j M Y'); + } + + return $from->format($from->year === $to->year ? 'j M' : 'j M Y').' – '.$to->format('j M Y'); + } + + /** + * The periods to choose from: the fixed ones and every year there are visits of. + * + * @return list + */ + private function ranges(): array + { + $ranges = []; + foreach (self::RANGES as $key => $label) { + $ranges[] = ['key' => $key, 'label' => $label]; + } + foreach (array_reverse($this->years()) as $year) { + $ranges[] = ['key' => (string) $year, 'label' => (string) $year]; + } + + return $ranges; + } + + /** @return list every year from the first visit until now */ + private function years(): array + { + $first = $this->firstDay(); + + return $first === null ? [] : range((int) substr($first, 0, 4), CarbonImmutable::now()->year); + } + + private function firstDay(): ?string + { + $first = DB::table($this->table('visits'))->min('day'); + + return is_string($first) ? substr($first, 0, 10) : null; + } + + /** + * @param int|null $untilHour only count visits that started in or before this hour of the day + * @return array{visitors: int, visits: int, page_views: int, average_seconds: int, bounce_rate: int} + */ + private function totals(string $from, string $to, ?int $untilHour = null): array + { + $row = $this->visits($from, $to) + ->when($untilHour !== null, fn (Builder $query) => $query->where('hour', '<=', $untilHour)) + ->selectRaw('count(*) as visits, count(distinct visitor_hash) as visitors, sum(page_views) as page_views') + ->selectRaw('sum(seconds) as seconds, sum(case when page_views <= 1 then 1 else 0 end) as bounces') + ->first(); + + $visits = self::number($row->visits ?? 0); + + return [ + 'visitors' => self::number($row->visitors ?? 0), + 'visits' => $visits, + 'page_views' => self::number($row->page_views ?? 0), + 'average_seconds' => $visits > 0 ? (int) round(self::number($row->seconds ?? 0) / $visits) : 0, + // Visits that ended after a single page, as a percentage. + 'bounce_rate' => $visits > 0 ? (int) round(100 * self::number($row->bounces ?? 0) / $visits) : 0, + ]; + } + + /** + * Visitors, visits and page views through time, one entry per hour, day, month + * or year. Every step of the period is there, also the ones without visits. + * + * `bot_hits` are the requests by programs; those have no hour, so per hour it stays 0. + * + * @return list + */ + private function series(string $from, string $to, string $bucket): array + { + $column = $bucket === 'hour' ? 'hour' : 'day'; + $rows = $this->visits($from, $to) + ->selectRaw("{$column} as step, count(*) as visits, count(distinct visitor_hash) as visitors, sum(page_views) as page_views") + ->groupBy($column) + ->get(); + + $steps = []; + $start = CarbonImmutable::parse($from); + $end = CarbonImmutable::parse($to); + + if ($bucket === 'hour') { + foreach (range(0, 23) as $hour) { + $steps[(string) $hour] = sprintf('%02d:00', $hour); + } + } elseif ($bucket === 'day') { + for ($date = $start; $date <= $end; $date = $date->addDay()) { + $steps[$date->toDateString()] = $date->format('j M'); + } + } elseif ($bucket === 'month') { + for ($date = $start->startOfMonth(); $date <= $end; $date = $date->addMonth()) { + $steps[$date->format('Y-m')] = $date->format('M Y'); + } + } else { + foreach (range($start->year, $end->year) as $year) { + $steps[(string) $year] = (string) $year; + } + } + + $series = []; + foreach ($steps as $key => $label) { + $series[(string) $key] = ['key' => (string) $key, 'label' => $label, 'visitors' => 0, 'visits' => 0, 'page_views' => 0, 'bot_hits' => 0]; + } + + $keyOf = fn (mixed $step): string => match ($bucket) { + 'hour' => (string) (int) (is_scalar($step) ? $step : 0), + 'day' => substr(is_scalar($step) ? (string) $step : '', 0, 10), + 'month' => substr(is_scalar($step) ? (string) $step : '', 0, 7), + default => substr(is_scalar($step) ? (string) $step : '', 0, 4), + }; + + foreach ($rows as $row) { + $key = $keyOf($row->step); + + if (isset($series[$key])) { + $series[$key]['visitors'] += self::number($row->visitors); + $series[$key]['visits'] += self::number($row->visits); + $series[$key]['page_views'] += self::number($row->page_views); + } + } + + if ($bucket !== 'hour') { + foreach ($this->botHits($from, $to)->selectRaw('day as step, sum(hits) as hits')->groupBy('day')->get() as $row) { + $key = $keyOf($row->step); + + if (isset($series[$key])) { + $series[$key]['bot_hits'] += self::number($row->hits); + } + } + } + + return array_values($series); + } + + /** + * The pages that were looked at most, with the average time on the page. + * + * @return list + */ + private function pages(string $from, string $to, ?int $limit = 10): array + { + $rows = DB::table($this->table('page_views'))->whereBetween('day', [$from, $to]) + ->selectRaw('path, max(post_id) as post_id, count(*) as views, sum(seconds) as seconds') + ->groupBy('path')->orderByDesc('views')->orderBy('path') + ->when($limit !== null, fn (Builder $query) => $query->limit((int) $limit))->get(); + + $titles = Manager::enabled('posts') ? Post::query()->whereIn('id', $rows->pluck('post_id')->filter()->all())->pluck('title', 'id') : collect(); + + $pages = []; + foreach ($rows as $row) { + $views = self::number($row->views); + $title = $titles->get(self::number($row->post_id)); + + $pages[] = [ + 'path' => is_string($row->path) ? $row->path : '', + 'title' => is_string($title) ? $title : null, + 'views' => $views, + 'average_seconds' => $views > 0 ? (int) round(self::number($row->seconds) / $views) : 0, + ]; + } + + return $pages; + } + + /** + * The posts that were read most. + * + * @return list + */ + private function posts(string $from, string $to): array + { + $rows = DB::table($this->table('page_views'))->whereBetween('day', [$from, $to])->whereNotNull('post_id') + ->selectRaw('post_id, count(*) as views, sum(seconds) as seconds') + ->groupBy('post_id')->orderByDesc('views')->limit(10)->get(); + + $found = Manager::enabled('posts') ? Post::query()->whereIn('id', $rows->pluck('post_id')->all())->get()->keyBy('id') : collect(); + + $posts = []; + foreach ($rows as $row) { + $post = $found->get(self::number($row->post_id)); + $views = self::number($row->views); + + if ($post instanceof Post) { + $posts[] = [ + 'title' => $post->title, + 'slug' => $post->slug, + 'views' => $views, + 'average_seconds' => $views > 0 ? (int) round(self::number($row->seconds) / $views) : 0, + ]; + } + } + + return $posts; + } + + /** + * Visits counted by one column of `visits`, most first. + * + * @return list + */ + private function grouped(string $from, string $to, string $column, int $limit): array + { + $rows = $this->visits($from, $to)->whereNotNull($column) + ->select("{$column} as name")->selectRaw('count(*) as visits') + ->groupBy($column)->orderByDesc('visits')->orderBy($column)->limit($limit)->get(); + + $result = []; + foreach ($rows as $row) { + $result[] = ['name' => is_scalar($row->name) ? (string) $row->name : '', 'visits' => self::number($row->visits)]; + } + + return $result; + } + + /** + * The four platforms the site shares posts to: how many visits came from each, + * and how many of those through a link the site posted itself. + * + * @return list + */ + private function platforms(string $from, string $to): array + { + $rows = $this->visits($from, $to)->whereIn('source', Source::PLATFORMS)->whereIn('channel', ['share', 'social']) + ->selectRaw('source, channel, count(*) as visits')->groupBy('source', 'channel')->get(); + + $platforms = []; + foreach (Source::PLATFORMS as $platform) { + $platforms[$platform] = ['name' => $platform, 'visits' => 0, 'shared' => 0]; + } + + foreach ($rows as $row) { + $name = is_string($row->source) ? $row->source : ''; + if (isset($platforms[$name])) { + $platforms[$name]['visits'] += self::number($row->visits); + $platforms[$name]['shared'] += $row->channel === 'share' ? self::number($row->visits) : 0; + } + } + + return array_values($platforms); + } + + /** + * The sites, search engines and platforms that sent visitors, most first. + * + * @return list + */ + private function sources(string $from, string $to, ?int $limit = 12): array + { + $rows = $this->visits($from, $to)->whereNotNull('source') + ->selectRaw('source, channel, count(*) as visits') + ->groupBy('source', 'channel')->orderByDesc('visits')->orderBy('source') + ->when($limit !== null, fn (Builder $query) => $query->limit((int) $limit))->get(); + + $sources = []; + foreach ($rows as $row) { + $sources[] = [ + 'name' => is_string($row->source) ? $row->source : '', + 'channel' => is_string($row->channel) ? $row->channel : '', + 'visits' => self::number($row->visits), + ]; + } + + return $sources; + } + + /** + * The busy moments: visits per weekday and hour of the day. + * + * @return list}> + */ + private function heatmap(string $from, string $to): array + { + $rows = $this->visits($from, $to)->selectRaw('weekday, hour, count(*) as visits')->groupBy('weekday', 'hour')->get(); + + $grid = []; + foreach (self::WEEKDAYS as $number => $name) { + $grid[$number] = ['day' => $name, 'hours' => array_fill(0, 24, 0)]; + } + + foreach ($rows as $row) { + $weekday = self::number($row->weekday); + $hour = self::number($row->hour); + if (isset($grid[$weekday]) && $hour >= 0 && $hour <= 23) { + $grid[$weekday]['hours'][$hour] = self::number($row->visits); + } + } + + return array_values($grid); + } + + /** + * The programs that fetched pages (search engines, AI crawlers, link previews, + * scripts ...): how often in all, which ones, what kind, and which pages. + * They are counted on the server (BotRecorder) and are never part of the + * visitors above. + * + * @param array{0: string, 1: string}|null $before the period to compare the total with + * @return array{total: int, previous: int|null, names: list, kinds: list, pages: list} + */ + private function bots(string $from, string $to, ?array $before): array + { + $names = []; + foreach ($this->botHits($from, $to)->selectRaw('bot, kind, sum(hits) as hits') + ->groupBy('bot', 'kind')->orderByDesc('hits')->orderBy('bot')->limit(15)->get() as $row) { + $names[] = ['name' => is_string($row->bot) ? $row->bot : '', 'kind' => is_string($row->kind) ? $row->kind : '', 'hits' => self::number($row->hits)]; + } + + $kinds = []; + foreach ($this->botHits($from, $to)->selectRaw('kind, sum(hits) as hits') + ->groupBy('kind')->orderByDesc('hits')->orderBy('kind')->get() as $row) { + $kinds[] = ['name' => is_string($row->kind) ? $row->kind : '', 'hits' => self::number($row->hits)]; + } + + $pages = []; + foreach ($this->botHits($from, $to)->selectRaw('path, sum(hits) as hits') + ->groupBy('path')->orderByDesc('hits')->orderBy('path')->limit(10)->get() as $row) { + $pages[] = ['path' => is_string($row->path) ? $row->path : '', 'hits' => self::number($row->hits)]; + } + + return [ + 'total' => self::number($this->botHits($from, $to)->sum('hits')), + 'previous' => $before === null ? null : self::number($this->botHits($before[0], $before[1])->sum('hits')), + 'names' => $names, + 'kinds' => $kinds, + 'pages' => $pages, + ]; + } + + /** + * Every program and page of the period, for the export. + * + * @return list> + */ + private function botRows(string $from, string $to): array + { + $rows = []; + foreach ($this->botHits($from, $to)->selectRaw('bot, kind, path, sum(hits) as hits') + ->groupBy('bot', 'kind', 'path')->orderByDesc('hits')->orderBy('bot')->orderBy('path')->get() as $row) { + $rows[] = [is_string($row->bot) ? $row->bot : '', is_string($row->kind) ? $row->kind : '', is_string($row->path) ? $row->path : '', self::number($row->hits)]; + } + + return $rows; + } + + /** + * How often each post was opened, since the beginning, and how those readers + * got to it. Someone who landed on the post is counted under the way they + * arrived (a shared post on LinkedIn, Google, direct ...); someone who was on + * another page of the site first and clicked through is counted as "internal". + * + * @param int|null $postId only this post + * @return array}> by post id + */ + public function readers(?int $postId = null): array + { + $views = $this->table('page_views'); + $visits = $this->table('visits'); + $rows = DB::table($views) + ->join($visits, "{$visits}.id", '=', "{$views}.visit_id") + ->whereNotNull("{$views}.post_id") + ->when($postId !== null, fn (Builder $query) => $query->where("{$views}.post_id", $postId)) + ->selectRaw("{$views}.post_id as post, case when {$visits}.entry_path = {$views}.path then {$visits}.channel else 'internal' end as arrived_by") + ->selectRaw("case when {$visits}.entry_path = {$views}.path then {$visits}.source else null end as arrived_from") + ->selectRaw("count(*) as views, sum({$views}.seconds) as seconds") + ->groupBy('post', 'arrived_by', 'arrived_from') + ->orderByDesc('views')->orderBy('arrived_by')->orderBy('arrived_from') + ->get(); + + $posts = []; + $seconds = []; + + foreach ($rows as $row) { + $id = self::number($row->post); + $views = self::number($row->views); + + $posts[$id] ??= ['views' => 0, 'average_seconds' => 0, 'sources' => []]; + $posts[$id]['views'] += $views; + $posts[$id]['sources'][] = [ + 'channel' => is_string($row->arrived_by) ? $row->arrived_by : '', + 'name' => is_string($row->arrived_from) ? $row->arrived_from : null, + 'views' => $views, + ]; + $seconds[$id] = ($seconds[$id] ?? 0) + self::number($row->seconds); + } + + foreach ($posts as $id => $post) { + $posts[$id]['average_seconds'] = $post['views'] > 0 ? (int) round(($seconds[$id] ?? 0) / $post['views']) : 0; + } + + return $posts; + } + + private function visits(string $from, string $to): Builder + { + return DB::table($this->table('visits'))->whereBetween('day', [$from, $to]); + } + + private function botHits(string $from, string $to): Builder + { + return DB::table($this->table('bot_hits'))->whereBetween('day', [$from, $to]); + } + + /** A count or sum as the database gives it (int, numeric string or null). */ + private function table(string $name): string + { + return config('manager.table_prefix').$name; + } + + private static function number(mixed $value): int + { + return is_numeric($value) ? (int) $value : 0; + } +} diff --git a/src/Modules/Statistics/StatisticsController.php b/src/Modules/Statistics/StatisticsController.php new file mode 100644 index 0000000..c5dbdb1 --- /dev/null +++ b/src/Modules/Statistics/StatisticsController.php @@ -0,0 +1,71 @@ +json($statistics->report($this->range($request), $this->choice($request))); + } + + /** One list of the period that is on the screen, as a CSV file. */ + public function export(Request $request, Statistics $statistics): StreamedResponse + { + $export = $statistics->export($request->string('sheet')->toString(), $this->range($request), $this->choice($request)); + + return response()->streamDownload(function () use ($export) { + $out = fopen('php://output', 'w'); + + if ($out === false) { + return; + } + + // The mark that tells a spreadsheet the file is UTF-8. + fwrite($out, "\xEF\xBB\xBF"); + fputcsv($out, $export['header'], ',', '"', ''); + + foreach ($export['rows'] as $row) { + fputcsv($out, array_map(self::cell(...), $row), ',', '"', ''); + } + + fclose($out); + }, $export['filename'], ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'no-store']); + } + + /** + * A page address, a referring site and the name of a program come from visitors. A spreadsheet + * runs a cell that starts like a formula, so such a cell gets a quote in front and is shown as + * the text it is. + */ + private static function cell(string|int $value): string|int + { + return is_string($value) && preg_match('/^[=+\-@\t\r]/', $value) === 1 ? "'".$value : $value; + } + + private function range(Request $request): string + { + return $request->string('range', Statistics::DEFAULT_RANGE)->toString(); + } + + /** @return array */ + private function choice(Request $request): array + { + $choice = []; + + foreach (['from', 'to', 'compare', 'compare_from'] as $key) { + $choice[$key] = $request->string($key)->limit(20, '')->toString(); + } + + // Nothing chosen is the period before, not "nothing". + if ($choice['compare'] === '') { + unset($choice['compare']); + } + + return $choice; + } +} diff --git a/src/Modules/Statistics/StatisticsModule.php b/src/Modules/Statistics/StatisticsModule.php new file mode 100644 index 0000000..d8d357f --- /dev/null +++ b/src/Modules/Statistics/StatisticsModule.php @@ -0,0 +1,79 @@ + 'Statistics', 'route' => 'manager.statistics.index', 'permission' => 'statistics.view']]; + } + + public function commands(): array + { + return [ForgetVisitorKeys::class]; + } + + public function actions(): array + { + return ['statistics.export' => ['Exported the statistics', ['sheet']]]; + } + + public function views(): array + { + return ['statistics.index' => 'Opened the statistics']; + } + + public function boot(): void + { + app()->singleton(CountedPages::class); + + // A person opens a few pages a minute; this only stops someone from flooding the statistics. + RateLimiter::for('manager-pulse', fn (Request $request) => Limit::perMinute(max(1, (int) config('manager.statistics.per_minute', 120)))->by((string) $request->ip())); + + // Programs never run the script that reports a view, so the server counts the pages it serves them. + // Through the kernel: it copies its own groups to the router when a request starts. + if (config('manager.statistics.count_bots') && method_exists($kernel = app(Kernel::class), 'appendMiddlewareToGroup')) { + $kernel->appendMiddlewareToGroup('web', CountBots::class); + } + + // Without yesterday's key, yesterday's visitor codes can no longer be traced back. + if (app()->runningInConsole()) { + app()->afterResolving(Schedule::class, fn (Schedule $schedule) => $schedule->command(ForgetVisitorKeys::class)->dailyAt('00:05')); + } + } +} diff --git a/src/Modules/Statistics/VisitRecorder.php b/src/Modules/Statistics/VisitRecorder.php new file mode 100644 index 0000000..1017a5e --- /dev/null +++ b/src/Modules/Statistics/VisitRecorder.php @@ -0,0 +1,168 @@ +page($path); + + if ($agent->isBot() || $page === null) { + return null; + } + + $now = now(); + $hash = hash('sha256', VisitorSalt::forToday().'|'.$ip.'|'.$userAgent); + + $visit = Visit::query() + ->where('visitor_hash', $hash) + ->where('last_seen_at', '>=', $now->copy()->subMinutes(self::VISIT_GAP_MINUTES)) + ->latest('id') + ->first(); + + if (! $visit instanceof Visit) { + $source = Source::of($arrival['via'] ?? '', $arrival['campaign'] ?? '', $arrival['referrer'] ?? '', $arrival['host'] ?? ''); + $country = strtoupper(trim($arrival['country'] ?? '')); + + $visit = Visit::query()->create([ + 'visitor_hash' => $hash, + 'started_at' => $now, + 'last_seen_at' => $now, + 'day' => $now->toDateString(), + 'hour' => $now->hour, + 'weekday' => $now->dayOfWeekIso, + 'entry_path' => $page['path'], + 'exit_path' => $page['path'], + 'channel' => $source->channel, + 'source' => $source->source, + 'referrer_host' => $source->referrerHost, + // Cloudflare says XX for unknown and T1 for Tor: neither is a country. + 'country' => preg_match('/^[A-Z]{2}$/', $country) === 1 && ! in_array($country, ['XX', 'T1'], true) ? $country : null, + 'device' => $agent->device(), + 'browser' => $agent->browser(), + 'os' => $agent->os(), + ]); + } + + $token = Str::random(40); + + PageView::query()->create([ + 'token' => $token, + 'visit_id' => $visit->id, + 'path' => $page['path'], + 'post_id' => $page['post_id'], + 'viewed_at' => $now, + 'day' => $now->toDateString(), + 'hour' => $now->hour, + ]); + + $visit->update([ + 'last_seen_at' => $now, + 'exit_path' => $page['path'], + 'page_views' => $visit->page_views + 1, + ]); + + return $token; + } + + /** + * Where the visit of this visitor came from (channel and source), for a request + * that is sent during it. Empty when the visit was not counted. + * + * @return array{channel?: string|null, source?: string|null} + */ + public function sourceOf(string $ip, string $userAgent): array + { + $visit = Visit::query() + ->where('visitor_hash', hash('sha256', VisitorSalt::forToday().'|'.$ip.'|'.$userAgent)) + ->latest('id') + ->first(); + + return $visit instanceof Visit ? ['channel' => $visit->channel, 'source' => $visit->source] : []; + } + + /** + * The time a visitor had a page in view, reported when they leave it. The + * browser may report more than once (a tab that is hidden and shown again), + * each time with the total so far. + */ + public function leave(string $token, int $seconds): void + { + $view = PageView::query()->where('token', $token)->first(); + + if (! $view instanceof PageView || $seconds < 1) { + return; + } + + // Never longer than the time that really passed since the page was opened. + $passed = (int) abs(now()->diffInSeconds($view->viewed_at)) + 5; + $seconds = min($seconds, $passed, self::MAX_SECONDS_ON_A_PAGE); + + if ($seconds <= $view->seconds) { + return; + } + + $view->update(['seconds' => $seconds]); + + Visit::query()->whereKey($view->visit_id)->update([ + 'seconds' => (int) PageView::query()->where('visit_id', $view->visit_id)->sum('seconds'), + 'last_seen_at' => now(), + ]); + } + + /** The address as the statistics know it, or null when it is no public page of this site. */ + public function pathOf(string $path): ?string + { + return $this->page($path)['path'] ?? null; + } + + /** + * The page behind an address, or null when the address is not a public page + * of this site: that keeps made-up addresses out of the statistics. + * + * @return array{path: string, post_id: int|null}|null + */ + private function page(string $path): ?array + { + if (! str_starts_with($path, '/')) { + return null; + } + + $path = '/'.trim(Str::before($path, '?'), '/'); + + if (strlen($path) > 255) { + return null; + } + + return app(CountedPages::class)->resolve($path); + } +} diff --git a/src/Modules/Statistics/migrations/2026_12_04_000004_create_manager_statistics_tables.php b/src/Modules/Statistics/migrations/2026_12_04_000004_create_manager_statistics_tables.php new file mode 100644 index 0000000..9cc43b3 --- /dev/null +++ b/src/Modules/Statistics/migrations/2026_12_04_000004_create_manager_statistics_tables.php @@ -0,0 +1,97 @@ +date('day')->primary(); + $table->string('salt', 64); + }); + + // One visit: the pages someone looks at with less than half an hour between them. + Schema::create($prefix.'visits', function (Blueprint $table) { + $table->id(); + $table->string('visitor_hash', 64); + $table->dateTime('started_at'); + $table->dateTime('last_seen_at'); + $table->date('day'); + $table->unsignedTinyInteger('hour'); + // 1 = Monday ... 7 = Sunday. + $table->unsignedTinyInteger('weekday'); + $table->string('entry_path'); + $table->string('exit_path'); + // direct, search, social, referral, share or campaign. + $table->string('channel', 20); + // The platform or site behind the channel: "linkedin", "google", "example.com". + $table->string('source', 80)->nullable(); + $table->string('referrer_host')->nullable(); + $table->string('country', 2)->nullable(); + $table->string('device', 10); + $table->string('browser', 30); + $table->string('os', 20); + $table->unsignedInteger('page_views')->default(0); + $table->unsignedInteger('seconds')->default(0); + + $table->index('day'); + $table->index(['visitor_hash', 'last_seen_at']); + }); + + Schema::create($prefix.'page_views', function (Blueprint $table) use ($prefix) { + $table->id(); + // What the browser sends back when the visitor leaves the page, to report the time spent. + $table->string('token', 40)->unique(); + $table->foreignId('visit_id')->constrained($prefix.'visits')->cascadeOnDelete(); + $table->string('path'); + // The post behind the page, when the posts module is on. No foreign key: posts may be off. + $table->unsignedBigInteger('post_id')->nullable(); + $table->dateTime('viewed_at'); + $table->date('day'); + $table->unsignedTinyInteger('hour'); + $table->unsignedInteger('seconds')->default(0); + + $table->index('day'); + $table->index('path'); + }); + + // How often each program (search engine, AI crawler, link preview, ...) fetched each page, per + // day. A counter, not a log: no address, no browser line. + Schema::create($prefix.'bot_hits', function (Blueprint $table) { + $table->id(); + $table->date('day'); + $table->string('bot', 60); + // search, ai, seo, social, monitor, feed, archive, scanner, script or other. + $table->string('kind', 20); + $table->string('path'); + $table->unsignedInteger('hits')->default(0); + + $table->unique(['day', 'bot', 'path']); + }); + } + + public function down(): void + { + $prefix = config('manager.table_prefix'); + + foreach (['bot_hits', 'page_views', 'visits', 'visitor_salts'] as $table) { + Schema::dropIfExists($prefix.$table); + } + } +}; diff --git a/src/Modules/Statistics/public-routes.php b/src/Modules/Statistics/public-routes.php new file mode 100644 index 0000000..dcc0140 --- /dev/null +++ b/src/Modules/Statistics/public-routes.php @@ -0,0 +1,10 @@ +middleware('throttle:manager-pulse')->group(function () { + Route::post('/view', [PulseController::class, 'view'])->name('manager.pulse.view'); + Route::post('/leave', [PulseController::class, 'leave'])->name('manager.pulse.leave'); +}); diff --git a/src/Modules/Statistics/routes.php b/src/Modules/Statistics/routes.php new file mode 100644 index 0000000..6086467 --- /dev/null +++ b/src/Modules/Statistics/routes.php @@ -0,0 +1,7 @@ +name('statistics.index')->middleware('can:statistics.view'); +Route::get('/statistics/export', [StatisticsController::class, 'export'])->name('statistics.export')->middleware('can:statistics.view'); diff --git a/tests/AuditOnTestCase.php b/tests/AuditOnTestCase.php index 33fd23d..54320d9 100644 --- a/tests/AuditOnTestCase.php +++ b/tests/AuditOnTestCase.php @@ -5,7 +5,7 @@ namespace IriksIT\Manager\Tests; /** A site that switched the optional audit log on (and reviews, so every module is on). */ abstract class AuditOnTestCase extends TestCase { - protected array $modules = ['audit' => true, 'reviews' => true]; + protected array $modules = ['audit' => true, 'reviews' => true, 'statistics' => true]; protected function defineEnvironment($app): void { diff --git a/tests/Feature/StatisticsOffTest.php b/tests/Feature/StatisticsOffTest.php new file mode 100644 index 0000000..cc8210e --- /dev/null +++ b/tests/Feature/StatisticsOffTest.php @@ -0,0 +1,18 @@ +toBeFalse() + ->and(Route::has('manager.pulse.view'))->toBeFalse() + ->and(Schema::hasTable('manager_visits'))->toBeFalse() + ->and(Schema::hasTable('manager_bot_hits'))->toBeFalse() + ->and(Manager::permissionValues())->not->toContain('statistics.view'); + + $this->postJson('/pulse/view', ['path' => '/'])->assertNotFound(); +}); diff --git a/tests/Feature/StatisticsTest.php b/tests/Feature/StatisticsTest.php new file mode 100644 index 0000000..28123af --- /dev/null +++ b/tests/Feature/StatisticsTest.php @@ -0,0 +1,131 @@ +withHeaders(['User-Agent' => BROWSER, ...$headers])->postJson('/pulse/view', ['path' => '/', ...$payload]); +} + +describe('counting a page view', function () { + it('counts a page of the list, with how the visitor arrived, and keeps no address', function () { + $token = pulse(['referrer' => 'https://www.google.com/search?q=x'], ['CF-IPCountry' => 'NL'])->assertOk()->json('token'); + + $visit = Visit::sole(); + expect($token)->toBeString() + ->and($visit->entry_path)->toBe('/') + ->and($visit->channel)->toBe('search') + ->and($visit->country)->toBe('NL') + ->and($visit->browser)->toBe('Firefox') + ->and($visit->page_views)->toBe(1) + ->and(PageView::sole()->token)->toBe($token); + + expect(json_encode(DB::table('manager_visits')->get()))->not->toContain('127.0.0.1')->not->toContain('Firefox/130'); + }); + + it('puts the next page in the same visit', function () { + pulse(); + pulse(['path' => '/about']); + + expect(Visit::count())->toBe(1)->and(Visit::sole()->page_views)->toBe(2)->and(Visit::sole()->exit_path)->toBe('/about'); + }); + + it('ignores an address that is not a page, a program, and a browser that asks not to be followed', function () { + expect(pulse(['path' => '/made-up'])->json('token'))->toBeNull(); + expect(pulse([], ['User-Agent' => 'Googlebot/2.1'])->json('token'))->toBeNull(); + expect(pulse([], ['DNT' => '1'])->json('token'))->toBeNull(); + expect(pulse([], ['Sec-GPC' => '1'])->json('token'))->toBeNull(); + + expect(Visit::count())->toBe(0); + }); + + it('counts a published post under the posts path, and not a draft', function () { + Post::create(['title' => 'Live', 'slug' => 'live', 'body' => 'x', 'published_at' => now()->subDay()]); + Post::create(['title' => 'Draft', 'slug' => 'draft', 'body' => 'x']); + + expect(pulse(['path' => '/blog/live'])->json('token'))->toBeString(); + expect(pulse(['path' => '/blog/draft'])->json('token'))->toBeNull(); + expect(PageView::sole()->post_id)->toBe(Post::where('slug', 'live')->value('id')); + }); + + it('asks the resolvers of the site for the rest', function () { + app(CountedPages::class)->register(fn (string $path) => $path === '/shop/1' ? ['path' => $path, 'post_id' => null] : null); + + expect(pulse(['path' => '/shop/1'])->json('token'))->toBeString(); + expect(pulse(['path' => '/shop/2'])->json('token'))->toBeNull(); + }); + + it('records the time on a page, never longer than has passed', function () { + $token = pulse()->json('token'); + + $this->travel(20)->seconds(); + $this->postJson('/pulse/leave', ['token' => $token, 'seconds' => 9999])->assertNoContent(); + + expect(PageView::sole()->seconds)->toBeLessThanOrEqual(30)->and(Visit::sole()->seconds)->toBe(PageView::sole()->seconds); + }); + + it('makes a new visitor code every day and forgets the old keys', function () { + pulse(); + $this->travel(1)->days(); + pulse(); + + expect(Visit::distinct()->count('visitor_hash'))->toBe(2)->and(VisitorSalt::count())->toBe(1); + + $this->artisan('manager:forget-visitor-keys')->assertSuccessful(); + }); +}); + +describe('programs', function () { + it('counts a page that was served to a program, per day, and nothing about the program', function () { + Route::middleware('web')->get('/robots-test', fn () => 'ok')->name('robots-test'); + + $this->withHeaders(['User-Agent' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'])->get('/robots-test')->assertOk(); + $this->withHeaders(['User-Agent' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'])->get('/robots-test')->assertOk(); + $this->withHeaders(['User-Agent' => BROWSER])->get('/robots-test')->assertOk(); + + $row = DB::table('manager_bot_hits')->sole(); + expect($row->hits)->toBe(2)->and($row->kind)->toBe('search')->and($row->path)->toBe('/robots-test'); + }); +}); + +describe('the report', function () { + it('needs statistics.view', function () { + $this->actingAs(makeUser()); + $this->getJson('/manager/statistics')->assertForbidden(); + $this->get('/manager/statistics/export?sheet=days')->assertForbidden(); + }); + + it('shows the totals, pages and channels of the period', function () { + pulse(['referrer' => 'https://www.google.com/']); + pulse(['path' => '/about']); + $this->actingAs(makeUser(['statistics.view'])); + + $this->getJson('/manager/statistics?range=today')->assertOk() + ->assertJsonPath('totals.visits', 1) + ->assertJsonPath('totals.page_views', 2) + ->assertJsonCount(2, 'pages') + ->assertJsonPath('channels.0.name', 'search'); + }); + + it('downloads a sheet as CSV', function () { + app(CountedPages::class)->register(fn (string $path) => $path === '/=1+1' ? ['path' => $path, 'post_id' => null] : null); + pulse(['path' => '/=1+1']); + $this->actingAs(makeUser(['statistics.view'])); + + $response = $this->get('/manager/statistics/export?sheet=pages&range=today')->assertOk(); + expect($response->headers->get('Content-Type'))->toContain('text/csv') + ->and($response->streamedContent())->toContain('/=1+1,,1,'); + }); +}); diff --git a/tests/StatisticsOnTestCase.php b/tests/StatisticsOnTestCase.php new file mode 100644 index 0000000..5b34de5 --- /dev/null +++ b/tests/StatisticsOnTestCase.php @@ -0,0 +1,18 @@ + true]; + + protected function defineEnvironment($app): void + { + parent::defineEnvironment($app); + + $app['config']->set('manager.statistics.pages', ['/', '/about']); + $app['config']->set('manager.statistics.posts_path', '/blog'); + $app['config']->set('manager.statistics.country_header', 'CF-IPCountry'); + } +}