Update -> add new log and analytices users
This commit is contained in:
44
app/models/Analytics.php
Normal file
44
app/models/Analytics.php
Normal file
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
class Analytics
|
||||
{
|
||||
private PDO $pdo;
|
||||
|
||||
public function __construct(PDO $pdo)
|
||||
{
|
||||
$this->pdo = $pdo;
|
||||
}
|
||||
|
||||
public function record(string $event, ?string $pasteId = null, array $extra = []): void
|
||||
{
|
||||
try {
|
||||
$stmt = $this->pdo->prepare(
|
||||
'INSERT INTO analytics (event, paste_id, ip, user_agent, referer, extra)
|
||||
VALUES (?, ?, ?, ?, ?, ?)'
|
||||
);
|
||||
$stmt->execute([
|
||||
$event,
|
||||
$pasteId,
|
||||
$this->getClientIp(),
|
||||
substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 512),
|
||||
substr($_SERVER['HTTP_REFERER'] ?? '', 0, 512),
|
||||
empty($extra) ? null : json_encode($extra, JSON_UNESCAPED_UNICODE),
|
||||
]);
|
||||
} catch (PDOException $e) {
|
||||
// analytics failure must never break the app
|
||||
}
|
||||
}
|
||||
|
||||
private function getClientIp(): string
|
||||
{
|
||||
foreach (['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'] as $key) {
|
||||
if (!empty($_SERVER[$key])) {
|
||||
$ip = trim(explode(',', $_SERVER[$key])[0]);
|
||||
if (filter_var($ip, FILTER_VALIDATE_IP)) {
|
||||
return $ip;
|
||||
}
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user