You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/SiteAnalyticsRecorder.php

369 lines
12 KiB
PHP

<?php
namespace App\Services;
use App\Models\SiteVisitEvent;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class SiteAnalyticsRecorder
{
private const VISITOR_COOKIE = 'site_visitor_id';
private const SESSION_COOKIE = 'site_visit_session';
private const VISITOR_TTL = 31536000;
private const SESSION_TTL = 1800;
public static function isTrackableRequest(ServerRequestInterface $request)
{
if (strtoupper($request->getMethod()) !== 'GET') {
return false;
}
$path = self::normalizePath($request->getUri()->getPath());
$blockedPrefixes = [
'/admin',
'/api',
'/internal',
'/link',
'/paytaro',
'/stripe',
'/yipay',
'/paid-registration',
'/password',
'/telegram_callback',
];
foreach ($blockedPrefixes as $prefix) {
if ($path === $prefix || strpos($path, $prefix . '/') === 0) {
return false;
}
}
$lowerPath = strtolower($path);
$blockedPaths = [
'/auth/logout',
'/user/logout',
'/user/code_check',
];
if (in_array($lowerPath, $blockedPaths, true)) {
return false;
}
if (strpos($path, '/auth/') === 0 && !in_array($path, ['/auth/login', '/auth/register'], true)) {
return false;
}
if (in_array($path, ['/404', '/405', '/500'], true)) {
return false;
}
if (preg_match('/\.(?:css|js|map|png|jpe?g|gif|webp|svg|ico|woff2?|ttf|eot|zip|gz|pdf|xml|txt)$/i', $path) === 1) {
return false;
}
if (strtolower($request->getHeaderLine('X-Requested-With')) === 'xmlhttprequest') {
return false;
}
$fetchMode = strtolower(trim($request->getHeaderLine('Sec-Fetch-Mode')));
if ($fetchMode !== '' && $fetchMode !== 'navigate') {
return false;
}
$fetchDestination = strtolower(trim($request->getHeaderLine('Sec-Fetch-Dest')));
if ($fetchDestination !== '' && !in_array($fetchDestination, ['document', 'iframe'], true)) {
return false;
}
$accept = strtolower($request->getHeaderLine('Accept'));
if ($accept !== ''
&& strpos($accept, 'text/html') === false
&& strpos($accept, 'application/xhtml+xml') === false
&& strpos($accept, '*/*') === false) {
return false;
}
return !self::isBot($request->getHeaderLine('User-Agent'));
}
public static function resolveIdentity(ServerRequestInterface $request)
{
$cookies = $request->getCookieParams();
$visitorId = isset($cookies[self::VISITOR_COOKIE]) ? strtolower((string) $cookies[self::VISITOR_COOKIE]) : '';
$sessionId = isset($cookies[self::SESSION_COOKIE]) ? strtolower((string) $cookies[self::SESSION_COOKIE]) : '';
$visitorNew = !self::validIdentifier($visitorId);
$sessionNew = !self::validIdentifier($sessionId);
if ($visitorNew) {
$visitorId = bin2hex(random_bytes(16));
}
if ($sessionNew) {
$sessionId = bin2hex(random_bytes(16));
}
return [
'visitor_id' => $visitorId,
'session_id' => $sessionId,
'visitor_new' => $visitorNew,
'session_new' => $sessionNew,
];
}
public static function withIdentityCookies(
ResponseInterface $response,
ServerRequestInterface $request,
array $identity
) {
$secure = self::isSecureRequest($request);
if (!empty($identity['visitor_new'])) {
$response = $response->withAddedHeader(
'Set-Cookie',
self::cookie(self::VISITOR_COOKIE, $identity['visitor_id'], self::VISITOR_TTL, $secure)
);
}
$response = $response->withAddedHeader(
'Set-Cookie',
self::cookie(self::SESSION_COOKIE, $identity['session_id'], self::SESSION_TTL, $secure)
);
return $response;
}
public static function recordPageView(
ServerRequestInterface $request,
array $identity,
$statusCode = 200,
array $userContext = []
)
{
$siteHost = self::requestHost($request);
if ($siteHost === '') {
return false;
}
$payload = self::basePayload($request, $identity, $userContext);
$payload['event_key'] = hash(
'sha256',
'pageview|'
. $identity['session_id'] . '|'
. $siteHost . '|'
. $payload['landing_path'] . '|'
. microtime(true) . '|'
. bin2hex(random_bytes(12))
);
$payload['event_type'] = 'visit';
$payload['status_code'] = max(0, min(999, (int) $statusCode));
return self::insert($payload);
}
public static function resolveUserContext(ServerRequestInterface $request)
{
$context = ['user_id' => 0, 'is_admin' => false];
$cookies = $request->getCookieParams();
$driver = strtolower((string) Config::get('authDriver', 'redis'));
$cookieName = $driver === 'cookie' ? 'uid' : ($driver === 'jwt' ? 'token' : 'sid');
if (!isset($cookies[$cookieName]) || trim((string) $cookies[$cookieName]) === '') {
return $context;
}
try {
$user = Auth::getUser();
if ($user === null || empty($user->isLogin) || !isset($user->id)) {
return $context;
}
$context['user_id'] = max(0, (int) $user->id);
if (method_exists($user, 'isAdmin')) {
$context['is_admin'] = (bool) $user->isAdmin();
} elseif (isset($user->is_admin)) {
$context['is_admin'] = !empty($user->is_admin);
}
} catch (\Throwable $exception) {
}
return $context;
}
private static function basePayload(ServerRequestInterface $request, array $identity, array $userContext)
{
$now = time();
$ip = self::text($request->getServerParam('REMOTE_ADDR', ''), 64);
$userAgent = self::text($request->getHeaderLine('User-Agent'), 500);
$device = self::deviceDetails($userAgent);
$query = $request->getQueryParams();
return [
'event_key' => '',
'event_type' => '',
'visitor_id' => (string) $identity['visitor_id'],
'session_id' => (string) $identity['session_id'],
'user_id' => isset($userContext['user_id'])
? max(0, (int) $userContext['user_id'])
: self::resolveUserContext($request)['user_id'],
'site_host' => self::requestHost($request),
'landing_path' => self::normalizePath($request->getUri()->getPath()),
'referrer_host' => self::referrerHost($request),
'ip_address' => $ip,
'ip_hash' => hash_hmac(
'sha256',
date('Y-m-d', $now) . '|' . $ip,
(string) Config::get('key', 'site-analytics')
),
'user_agent' => $userAgent,
'browser' => $device['browser'],
'operating_system' => $device['operating_system'],
'device_type' => $device['device_type'],
'utm_source' => self::queryValue($query, 'utm_source'),
'utm_medium' => self::queryValue($query, 'utm_medium'),
'utm_campaign' => self::queryValue($query, 'utm_campaign'),
'status_code' => 0,
'occurred_at' => $now,
'created_at' => $now,
];
}
private static function insert(array $payload)
{
try {
return SiteVisitEvent::query()->insertOrIgnore($payload) > 0;
} catch (\Throwable $exception) {
return false;
}
}
private static function requestHost(ServerRequestInterface $request)
{
$host = $request->getUri()->getHost();
if ($host === '') {
$host = preg_replace('/:\d+$/', '', trim($request->getHeaderLine('Host')));
}
return SiteAnalyticsService::normalizeHost($host);
}
private static function referrerHost(ServerRequestInterface $request)
{
$referrer = trim($request->getHeaderLine('Referer'));
if ($referrer === '') {
return '(direct)';
}
$host = parse_url($referrer, PHP_URL_HOST);
if ($host === null || $host === false) {
return '(direct)';
}
$host = SiteAnalyticsService::normalizeHost($host);
return $host === '' ? '(direct)' : $host;
}
private static function normalizePath($path)
{
$path = '/' . ltrim((string) $path, '/');
$path = preg_replace('#/+#', '/', $path);
if ($path === null || $path === '') {
return '/';
}
return self::text($path, 255);
}
private static function queryValue(array $query, $key)
{
if (!isset($query[$key]) || is_array($query[$key])) {
return '';
}
return self::text($query[$key], 100);
}
private static function deviceDetails($userAgent)
{
$ua = strtolower((string) $userAgent);
if (strpos($ua, 'micromessenger') !== false) {
$browser = 'WeChat';
} elseif (strpos($ua, 'edg/') !== false || strpos($ua, 'edge/') !== false) {
$browser = 'Edge';
} elseif (strpos($ua, 'firefox/') !== false) {
$browser = 'Firefox';
} elseif (strpos($ua, 'chrome/') !== false || strpos($ua, 'crios/') !== false) {
$browser = 'Chrome';
} elseif (strpos($ua, 'safari/') !== false) {
$browser = 'Safari';
} else {
$browser = 'Other';
}
if (strpos($ua, 'iphone') !== false || strpos($ua, 'ipad') !== false || strpos($ua, 'ipod') !== false) {
$operatingSystem = 'iOS';
} elseif (strpos($ua, 'android') !== false) {
$operatingSystem = 'Android';
} elseif (strpos($ua, 'windows') !== false) {
$operatingSystem = 'Windows';
} elseif (strpos($ua, 'mac os') !== false || strpos($ua, 'macintosh') !== false) {
$operatingSystem = 'macOS';
} elseif (strpos($ua, 'linux') !== false) {
$operatingSystem = 'Linux';
} else {
$operatingSystem = 'Other';
}
if (strpos($ua, 'ipad') !== false || strpos($ua, 'tablet') !== false) {
$deviceType = 'tablet';
} elseif (strpos($ua, 'mobile') !== false || strpos($ua, 'iphone') !== false || strpos($ua, 'android') !== false) {
$deviceType = 'mobile';
} else {
$deviceType = 'desktop';
}
return [
'browser' => $browser,
'operating_system' => $operatingSystem,
'device_type' => $deviceType,
];
}
private static function isBot($userAgent)
{
$userAgent = strtolower(trim((string) $userAgent));
if ($userAgent === '') {
return false;
}
return preg_match(
'/bot|crawler|spider|slurp|bingpreview|facebookexternalhit|headlesschrome|python-requests|curl\//',
$userAgent
) === 1;
}
private static function isSecureRequest(ServerRequestInterface $request)
{
if (strtolower($request->getUri()->getScheme()) === 'https') {
return true;
}
$https = strtolower((string) $request->getServerParam('HTTPS', ''));
return $https !== '' && $https !== 'off' && $https !== '0';
}
private static function cookie($name, $value, $maxAge, $secure)
{
$parts = [
$name . '=' . $value,
'Path=/',
'Max-Age=' . (int) $maxAge,
'Expires=' . gmdate('D, d M Y H:i:s', time() + (int) $maxAge) . ' GMT',
'HttpOnly',
'SameSite=Lax',
];
if ($secure) {
$parts[] = 'Secure';
}
return implode('; ', $parts);
}
private static function validIdentifier($value)
{
return preg_match('/^[a-f0-9]{32}$/D', strtolower((string) $value)) === 1;
}
private static function text($value, $limit)
{
$value = trim((string) $value);
$value = preg_replace('/[\x00-\x1F\x7F]/', '', $value);
if ($value === null) {
return '';
}
return function_exists('mb_substr')
? mb_substr($value, 0, (int) $limit, 'UTF-8')
: substr($value, 0, (int) $limit);
}
}