初始化版本
This commit is contained in:
63
api/save_text.php
Normal file
63
api/save_text.php
Normal file
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
// 保存讨论区文案到本地(避免重复),不进行过期清理
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
function respond($ok, $message = '', $path = '') {
|
||||
echo json_encode(['success' => $ok, 'message' => $message, 'path' => $path], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
exit;
|
||||
}
|
||||
|
||||
$raw = file_get_contents('php://input');
|
||||
$data = json_decode($raw, true);
|
||||
$text = trim($data['text'] ?? '');
|
||||
$source = trim($data['source'] ?? '');
|
||||
if ($text === '') { respond(false, '文本为空'); }
|
||||
|
||||
// 根目录
|
||||
$textsRoot = __DIR__ . '/../texts';
|
||||
if (!is_dir($textsRoot)) { @mkdir($textsRoot, 0777, true); }
|
||||
// 按来源(/后缀,即 yiyan/dujitang/renjian 等)创建子目录
|
||||
$safeSource = preg_replace('/[^A-Za-z0-9._-]+/u', '_', $source ?: 'unknown');
|
||||
$safeSource = trim($safeSource, '._-');
|
||||
if ($safeSource === '') { $safeSource = 'unknown'; }
|
||||
|
||||
// 日期目录
|
||||
$today = (new DateTime('now'))->format('Y-m-d');
|
||||
$targetDir = $textsRoot . '/' . $safeSource . '/' . $today;
|
||||
if (!is_dir($targetDir)) { @mkdir($targetDir, 0777, true); }
|
||||
|
||||
// 改为保存到同一天的单个文件 all.json
|
||||
$targetPath = $targetDir . '/all.json';
|
||||
|
||||
// 读取已有数据
|
||||
$entries = [];
|
||||
if (file_exists($targetPath)) {
|
||||
$rawJson = @file_get_contents($targetPath);
|
||||
$decoded = json_decode($rawJson, true);
|
||||
if (is_array($decoded)) { $entries = $decoded; }
|
||||
}
|
||||
|
||||
// 重复检查:文本完全相同则认为重复
|
||||
foreach ($entries as $e) {
|
||||
if (isset($e['text']) && trim((string)$e['text']) === $text) {
|
||||
respond(true, '文本已存在,跳过保存', str_replace($_SERVER['DOCUMENT_ROOT'], '', $targetPath));
|
||||
}
|
||||
}
|
||||
|
||||
$entries[] = [
|
||||
'text' => $text,
|
||||
'source' => $source,
|
||||
'created_at' => (new DateTime('now'))->format(DateTime::ATOM),
|
||||
];
|
||||
|
||||
try {
|
||||
$json = json_encode($entries, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
|
||||
if (@file_put_contents($targetPath, $json, LOCK_EX) === false) {
|
||||
respond(false, '无法写入文件');
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
respond(false, '保存失败: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
respond(true, '保存成功', str_replace($_SERVER['DOCUMENT_ROOT'], '', $targetPath));
|
||||
|
||||
Reference in New Issue
Block a user