lndwrtshft / Protokoll /api /read_md.php
GermanDarkDEV's picture
Upload 24 files
1e1edce verified
Raw History Blame Contribute Delete
2.28 kB
<?php
// Sicheres Lesen von Markdown-Dateien, um CORS/Servereinschränkungen zu umgehen
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
function fail(string $msg, int $code = 400): void {
http_response_code($code);
echo json_encode([ 'status' => 'error', 'error' => $msg ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
try {
$raw = file_get_contents('php://input');
if ($raw === false) fail('Konnte Request-Body nicht lesen');
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
} catch (Throwable $e) {
fail('Ungültiger JSON-Body: ' . $e->getMessage());
}
$path = $data['path'] ?? null;
if (!is_string($path)) fail('Parameter path ist erforderlich');
$protokollDir = realpath(dirname(__DIR__));
$rootDir = realpath(dirname(dirname(__DIR__)));
if ($protokollDir === false || $rootDir === false) fail('Serverpfade nicht auflösbar', 500);
if (!preg_match('/\.md$/i', $path)) fail('Nur .md Dateien');
$targetAbs = null;
if (str_starts_with($path, './')) {
$rel = ltrim(substr($path, 2), '/\\');
$targetAbs = $protokollDir . DIRECTORY_SEPARATOR . $rel;
} elseif (str_starts_with($path, '../')) {
$rel = ltrim(substr($path, 3), '/\\');
$targetAbs = $rootDir . DIRECTORY_SEPARATOR . $rel;
} else {
fail('Ungültiges Pfadformat');
}
$targetReal = realpath($targetAbs);
if ($targetReal === false) fail('Datei nicht gefunden', 404);
$ext = strtolower(pathinfo($targetReal, PATHINFO_EXTENSION));
if ($ext !== 'md') fail('Nur .md Dateien');
$protokollPrefix = rtrim(str_replace('\\', '/', $protokollDir), '/') . '/';
$rootPrefix = rtrim(str_replace('\\', '/', $rootDir), '/') . '/';
$targetNorm = rtrim(str_replace('\\', '/', $targetReal), '/');
$allowed = false;
if (str_starts_with($targetNorm, $protokollPrefix)) {
$allowed = true;
} else if (str_starts_with($targetNorm, $rootPrefix)) {
$base = basename($targetNorm);
if (in_array($base, ['StartAIChatRegeln.md', 'StopAIChatRegeln.md'], true)) $allowed = true;
}
if (!$allowed) fail('Zugriff verweigert');
$content = @file_get_contents($targetReal);
if ($content === false) fail('Lesefehler', 500);
echo json_encode([ 'status' => 'ok', 'content' => $content ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);