Statistics module: visitor statistics without cookies
This commit is contained in:
1 parent
acb8620621
commit
7482ee489b
24 files changed
+1872
-4
No files matched your search
@@ -0,0 +1,745 @@
|
||||
<?php
|
||||
|
||||
namespace IriksIT\Manager\Modules\Statistics;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use IriksIT\Manager\Facades\Manager;
|
||||
use IriksIT\Manager\Models\Post;
|
||||
|
||||
/**
|
||||
* The numbers of the visitor statistics, for the manager. The only code that
|
||||
* reads `visits`, `page_views` and `bot_hits` for a report.
|
||||
*
|
||||
* The database only ever groups by the plain `day`, `hour` and `weekday`
|
||||
* columns; weeks, months and years are added up here. That keeps every query the
|
||||
* same on MySQL and on SQLite (the tests).
|
||||
*
|
||||
* "Visitors" are counted per day: the visitor code changes at midnight, so
|
||||
* someone who comes back the next day is a new visitor.
|
||||
*/
|
||||
final class Statistics
|
||||
{
|
||||
/** The periods the manager offers, next to one per year (as "2026"). */
|
||||
public const RANGES = [
|
||||
'today' => '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<string, string> $choice `from` and `to` for a period of one's own, `compare` (see COMPARISONS) and `compare_from`
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
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<array{key: string, label: string, visitors: int, visits: int, page_views: int, bot_hits: int}>, pages: list<array{path: string, title: string|null, views: int, average_seconds: int}>, posts: list<array{title: string, slug: string, views: int, average_seconds: int}>, channels: list<array{name: string, visits: int}>}
|
||||
*/
|
||||
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<string, string> $choice
|
||||
* @return array{filename: string, header: list<string>, rows: list<list<string|int>>}
|
||||
*/
|
||||
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<array{key: string, label: string, visitors: int, page_views: int, previous_visitors: int}>, days: list<array{key: string, label: string, visitors: int, visits: int, page_views: int, bot_hits: int}>}
|
||||
*/
|
||||
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<string, string> $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<string, string> $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<array{key: string, label: string}>
|
||||
*/
|
||||
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<int> 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<array{key: string, label: string, visitors: int, visits: int, page_views: int, bot_hits: int}>
|
||||
*/
|
||||
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<array{path: string, title: string|null, views: int, average_seconds: int}>
|
||||
*/
|
||||
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<array{title: string, slug: string, views: int, average_seconds: int}>
|
||||
*/
|
||||
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<array{name: string, visits: int}>
|
||||
*/
|
||||
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<array{name: string, visits: int, shared: int}>
|
||||
*/
|
||||
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<array{name: string, channel: string, visits: int}>
|
||||
*/
|
||||
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<array{day: string, hours: list<int>}>
|
||||
*/
|
||||
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<array{name: string, kind: string, hits: int}>, kinds: list<array{name: string, hits: int}>, pages: list<array{path: string, hits: int}>}
|
||||
*/
|
||||
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<list<string|int>>
|
||||
*/
|
||||
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<int, array{views: int, average_seconds: int, sources: list<array{channel: string, name: string|null, views: int}>}> 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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user