1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
<?php
// api/course/event.php — anonymous course telemetry. No IP/UA stored.
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: https://webx11.duckdns.org');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['error' => 'POST only']); exit; }
$raw = file_get_contents('php://input');
if ($raw === false || strlen($raw) === 0) { http_response_code(400); echo json_encode(['error' => 'empty body']); exit; }
if (strlen($raw) > 4096) { http_response_code(413); echo json_encode(['error' => 'payload too large']); exit; }
$p = json_decode($raw, true);
if (!is_array($p)) { http_response_code(400); echo json_encode(['error' => 'invalid json']); exit; }
$sid = isset($p['sid']) ? substr(preg_replace('/[^a-zA-Z0-9_-]/', '', (string)$p['sid']), 0, 64) : '';
$type = isset($p['type']) ? (string)$p['type'] : '';
$allowed = ['lesson_open','lesson_complete','exercise_fail','question','project_open','project_view','quiz_answer'];
if (strlen($sid) < 8 || !in_array($type, $allowed, true)) { http_response_code(400); echo json_encode(['error' => 'sid/type invalid']); exit; }
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$dir = __DIR__ . '/../../data/course';
if (!is_dir($dir)) { mkdir($dir, 0775, true); }
$rlFile = $dir . '/.rl-' . substr(hash('sha256', $ip), 0, 16) . '-' . date('YmdH');
$hits = file_exists($rlFile) ? (int)file_get_contents($rlFile) : 0;
if ($hits > 120) { http_response_code(429); echo json_encode(['error' => 'rate limited']); exit; }
file_put_contents($rlFile, (string)($hits + 1), LOCK_EX);
if (random_int(1, 50) === 1) {
foreach (glob($dir . '/.rl-*') as $f) { if (filemtime($f) < time() - 172800) @unlink($f); }
}
$detail = isset($p['detail']) && is_array($p['detail']) ? array_slice($p['detail'], 0, 8, true) : [];
foreach ($detail as $k => $v) {
if (is_string($v)) $detail[$k] = substr($v, 0, 300);
elseif (is_scalar($v)) $detail[$k] = substr((string)$v, 0, 300);
else $detail[$k] = gettype($v);
}
$row = ['ts' => gmdate('c'), 'type' => $type, 'sid' => $sid,
'version' => substr((string)($p['version'] ?? ''), 0, 40), 'detail' => $detail];
$out = $dir . '/events-' . date('Ym') . '.jsonl';
$fp = fopen($out, 'a');
if ($fp && flock($fp, LOCK_EX)) { fwrite($fp, json_encode($row, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n"); flock($fp, LOCK_UN); fclose($fp); }
http_response_code(200);
echo json_encode(['ok' => true]);
|