169 lines
5.9 KiB
PHP
169 lines
5.9 KiB
PHP
<?php
|
|
|
|
namespace IriksIT\Manager\Modules\Statistics;
|
|
|
|
use Illuminate\Support\Str;
|
|
use IriksIT\Manager\Models\PageView;
|
|
use IriksIT\Manager\Models\Visit;
|
|
use IriksIT\Manager\Models\VisitorSalt;
|
|
use IriksIT\Manager\Support\UserAgent;
|
|
|
|
/**
|
|
* Writes down what the statistics are made of: a page that was looked at, the
|
|
* visit it belongs to, and how long the visitor stayed on it. The only code that
|
|
* writes to `visits` and `page_views`.
|
|
*
|
|
* The IP address and the browser line only go into the visitor code (see
|
|
* VisitorSalt); neither is stored.
|
|
*/
|
|
final class VisitRecorder
|
|
{
|
|
/** A page view more than this long after the previous one starts a new visit. */
|
|
public const VISIT_GAP_MINUTES = 30;
|
|
|
|
/** Nobody reads one page longer than this; a longer time is a tab left open. */
|
|
public const MAX_SECONDS_ON_A_PAGE = 1800;
|
|
|
|
/**
|
|
* Counts one page view. Returns the token the browser sends back when the
|
|
* visitor leaves the page, or null when this is not something to count: a
|
|
* program instead of a person, or an address that is not a page of the site.
|
|
*
|
|
* @param array{via?: string, campaign?: string, referrer?: string, country?: string, host?: string} $arrival how the visitor got here; only used for the first page of a visit
|
|
*/
|
|
public function view(string $ip, string $userAgent, string $path, array $arrival = []): ?string
|
|
{
|
|
$agent = new UserAgent($userAgent);
|
|
$page = $this->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);
|
|
}
|
|
}
|