65 lines
2.7 KiB
PHP
65 lines
2.7 KiB
PHP
<?php
|
|
/* gamelog endpoint — POST append (client) / GET fetch (viewer) / GET action=clear
|
|
เก็บเป็น JSONL ที่ data/log.jsonl (server.js เขียนตรง ๆ ด้วย; ไฟล์เดียวกัน) */
|
|
header('Content-Type: application/json; charset=utf-8');
|
|
$dir = __DIR__ . '/data';
|
|
$file = $dir . '/log.jsonl';
|
|
if (!is_dir($dir)) { @mkdir($dir, 0777, true); }
|
|
|
|
$method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
|
|
|
|
if ($method === 'POST') {
|
|
$raw = file_get_contents('php://input');
|
|
$j = json_decode($raw, true);
|
|
if (!is_array($j)) { echo json_encode(['ok' => false, 'err' => 'bad json']); exit; }
|
|
$items = (isset($j['items']) && is_array($j['items'])) ? $j['items'] : [$j];
|
|
$lines = '';
|
|
foreach ($items as $it) {
|
|
if (!is_array($it)) continue;
|
|
$rec = [
|
|
't' => isset($it['t']) ? (int)$it['t'] : (int)(microtime(true) * 1000),
|
|
'cat' => mb_substr((string)(isset($it['cat']) ? $it['cat'] : 'อื่นๆ'), 0, 24),
|
|
'room' => mb_substr((string)(isset($it['room']) ? $it['room'] : ''), 0, 64),
|
|
'who' => mb_substr((string)(isset($it['who']) ? $it['who'] : ''), 0, 48),
|
|
'ev' => mb_substr((string)(isset($it['ev']) ? $it['ev'] : ''), 0, 48),
|
|
'detail' => mb_substr((string)(isset($it['detail']) ? $it['detail'] : ''), 0, 500),
|
|
'src' => mb_substr((string)(isset($it['src']) ? $it['src'] : 'client'), 0, 12),
|
|
];
|
|
$lines .= json_encode($rec, JSON_UNESCAPED_UNICODE) . "\n";
|
|
}
|
|
if ($lines !== '') @file_put_contents($file, $lines, FILE_APPEND | LOCK_EX);
|
|
/* ring trim กันไฟล์ใหญ่เกิน */
|
|
if (@filesize($file) > 4000000) {
|
|
$all = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
|
if ($all && count($all) > 5000) {
|
|
$all = array_slice($all, -5000);
|
|
@file_put_contents($file, implode("\n", $all) . "\n", LOCK_EX);
|
|
}
|
|
}
|
|
echo json_encode(['ok' => true]);
|
|
exit;
|
|
}
|
|
|
|
if (isset($_GET['action']) && $_GET['action'] === 'clear') {
|
|
@file_put_contents($file, '', LOCK_EX);
|
|
echo json_encode(['ok' => true]);
|
|
exit;
|
|
}
|
|
|
|
/* GET: คืน log (กรองตาม cat) ล่าสุดก่อน */
|
|
$cat = isset($_GET['cat']) ? $_GET['cat'] : '';
|
|
$limit = isset($_GET['limit']) ? min(3000, max(1, (int)$_GET['limit'])) : 800;
|
|
$out = [];
|
|
if (is_file($file)) {
|
|
$all = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
|
if ($all) {
|
|
for ($i = count($all) - 1; $i >= 0 && count($out) < $limit; $i--) {
|
|
$r = json_decode($all[$i], true);
|
|
if (!is_array($r)) continue;
|
|
if ($cat && $cat !== 'ALL' && (!isset($r['cat']) || $r['cat'] !== $cat)) continue;
|
|
$out[] = $r;
|
|
}
|
|
}
|
|
}
|
|
echo json_encode(['ok' => true, 'logs' => $out, 'count' => count($out)]);
|