Portfolio_pero/api/track.php
2026-09-03 13:27:06 +02:00

144 lines
4.5 KiB
PHP

<?php
/**
* Tracking des visites sans cookies.
*/
require_once __DIR__ . '/../includes/Security.php';
require_once __DIR__ . '/../config/bootstrap.php';
require_once __DIR__ . '/../config/database.php';
Security::bootstrap(false, ['api' => true, 'no_store' => true]);
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
Security::jsonResponse(['ok' => false]);
}
Security::enforceSameOrigin(true);
$rawBody = file_get_contents('php://input');
$data = json_decode($rawBody ?: '', true);
if (!is_array($data)) {
http_response_code(400);
Security::jsonResponse(['ok' => false]);
}
$action = (string) ($data['action'] ?? '');
$sessionId = (string) ($data['session_id'] ?? '');
$page = (string) ($data['page'] ?? '/');
$referrer = $data['referrer'] ?? null;
$duration = isset($data['duration']) ? (int) $data['duration'] : null;
$device = (string) ($data['device'] ?? 'desktop');
$projectId = isset($data['project_id']) ? (int) $data['project_id'] : 0;
if (!preg_match('/^[a-z0-9]{8,64}$/i', $sessionId)) {
http_response_code(400);
Security::jsonResponse(['ok' => false]);
}
$page = mb_substr((string) preg_replace('/[^\x20-\x7E]/', '', $page), 0, 500);
$referrer = is_string($referrer)
? mb_substr((string) preg_replace('/[^\x20-\x7E]/', '', $referrer), 0, 500)
: null;
$device = in_array($device, ['desktop', 'mobile', 'tablet'], true) ? $device : 'desktop';
$ip = Security::clientIp();
$salt = config_required('analytics_salt');
$ipHash = hash('sha256', $ip . $salt);
$ua = strtolower((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''));
$botPatterns = ['bot', 'crawler', 'spider', 'curl', 'wget', 'python', 'java', 'go-http'];
foreach ($botPatterns as $pattern) {
if (str_contains($ua, $pattern)) {
Security::jsonResponse(['ok' => true, 'skipped' => 'bot']);
}
}
try {
$db = getDatabase();
if (Security::isRateLimited($db, 'track', $ip, 240, 10)) {
Security::jsonResponse(['ok' => true, 'skipped' => 'rate_limited']);
}
Security::recordAttempt($db, 'track', $ip);
switch ($action) {
case 'visit':
$check = $db->prepare(
'SELECT id FROM visits
WHERE session_id = :sid AND page = :page
AND created_at > NOW() - INTERVAL 5 MINUTE
LIMIT 1'
);
$check->execute([
'sid' => $sessionId,
'page' => $page,
]);
if ($check->fetchColumn()) {
Security::jsonResponse(['ok' => true, 'skipped' => 'duplicate']);
}
$db->prepare(
'INSERT INTO visits (ip_hash, session_id, page, referrer, device_type)
VALUES (:ip, :sid, :page, :ref, :device)'
)->execute([
'ip' => $ipHash,
'sid' => $sessionId,
'page' => $page,
'ref' => $referrer,
'device' => $device,
]);
break;
case 'duration':
if ($duration !== null && $duration > 0 && $duration < 86400) {
$db->prepare(
'UPDATE visits
SET duration_s = :duration
WHERE session_id = :sid
ORDER BY created_at DESC
LIMIT 1'
)->execute([
'duration' => $duration,
'sid' => $sessionId,
]);
}
break;
case 'project_click':
if ($projectId > 0) {
$db->prepare(
'INSERT INTO project_clicks (project_id, ip_hash)
VALUES (:project_id, :ip_hash)'
)->execute([
'project_id' => $projectId,
'ip_hash' => $ipHash,
]);
}
break;
default:
http_response_code(400);
Security::jsonResponse(['ok' => false, 'error' => 'unknown_action']);
}
if (random_int(1, 100) === 1) {
try {
$db->exec("DELETE FROM visits WHERE created_at < NOW() - INTERVAL 13 MONTH");
$db->exec("DELETE FROM project_clicks WHERE created_at < NOW() - INTERVAL 13 MONTH");
} catch (Throwable) {
}
}
Security::jsonResponse(['ok' => true]);
} catch (Throwable $e) {
error_log('[Track] ' . $e->getMessage());
http_response_code(500);
Security::jsonResponse(['ok' => false]);
}