/
al.anatolyev
/
web4stud
Обзор
Документация
Войти
/
al.anatolyev
/
web4stud
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
tools/md2html.php
137 строк
4 KB
aag
%1
19 май 2026, 12:36
19 май 2026, 12:36
1775bad
Код
Авторство
О чём код?
<?php declare(strict_types=1); // ========================================== // КОНФИГУРАЦИЯ // ========================================== define('MD_DIR', __DIR__ . '/markdown'); define('HTML_DIR', __DIR__ . '/html_output'); // Создаём директории, если их нет foreach ([MD_DIR, HTML_DIR] as $dir) { if (!is_dir($dir)) { mkdir($dir, 0755, true); } } // ========================================== // 1. ПРОВЕРКА ВХОДНЫХ ДАННЫХ // ========================================== $inputFile = $_GET['file'] ?? null; if (!$inputFile) { /* http_response_code(400); header('Content-Type: application/json'); echo json_encode(['error' => 'Параметр ?file= обязателен. Пример: ?file=report.md']); */ echo "error: Параметр ?file= обязателен. Пример: ?file=report.md"; exit; } // Безопасная очистка имени файла $safeName = basename($inputFile); // Разрешаем только .md if (strtolower(pathinfo($safeName, PATHINFO_EXTENSION)) !== 'md') { http_response_code(400); header('Content-Type: application/json'); echo json_encode(['error' => 'Разрешены только файлы с расширением .md']); exit; } // ========================================== // 2. ЗАЩИТА ОТ PATH TRAVERSAL // ========================================== $mdPath = realpath(MD_DIR . '/' . $safeName); $allowedRoot = realpath(MD_DIR); if ($mdPath === false || !str_starts_with($mdPath, $allowedRoot . '/')) { //http_response_code(403); //header('Content-Type: application/json'); //echo json_encode(['error' => 'Доступ запрещён. Файл должен находиться в директории markdown/']); echo "error: Файл должен находиться в директории markdown/"; exit; } if (!is_file($mdPath) || !is_readable($mdPath)) { http_response_code(404); header('Content-Type: application/json'); echo json_encode(['error' => 'Файл не найден в директории markdown/']); exit; } // Формируем путь для результата $htmlName = pathinfo($safeName, PATHINFO_FILENAME) . '.html'; $htmlPath = HTML_DIR . '/' . $htmlName; // ========================================== // 3. ФУНКЦИЯ КОНВЕРТАЦИИ // ========================================== function convertWithPandoc(string $mdPath, string $htmlPath): void { // Проверка pandoc exec('pandoc --version', $ver, $check); if ($check !== 0) { throw new RuntimeException('Pandoc не найден в PATH или не установлен.'); } // Формируем команду // I did $cmd = sprintf( //'pandoc -f markdown-raw_html --no-highlight %s -t html %s 2>&1', 'pandoc %s -f markdown --no-highlight -t html -o %s 2>&1', escapeshellarg($mdPath), escapeshellarg($htmlPath) ); /* qwen said $cmd = sprintf( 'pandoc %s -s -o %s 2>&1', escapeshellarg($mdPath), escapeshellarg($htmlPath) ); */ $output = []; $returnCode = 0; $i = $mdPath; $o = $htmlPath; $command = "pandoc $i -f markdown-raw_html --no-highlight -t html -o $o"; // OK, is a powerful method $command = "markdown < $i > $o"; // OK. Easy way //echo $command; exec($command); //exec("pandoc $i -f markdown --no-highlight -t html -o $o 2>&1"); //exec($cmd, $output, $returnCode); if ($returnCode !== 0) { throw new RuntimeException("Pandoc завершился с ошибкой (код $returnCode):\n" . implode("\n", $output)); } } // ========================================== // 4. ВЫПОЛНЕНИЕ // ========================================== convertWithPandoc($mdPath, $htmlPath); echo "✅ Успешно сконвертировано в: <a href='file://".HTML_DIR."/$htmlName'>file://".HTML_DIR."/$htmlName</a>\n"; exit; /// to get JSON try { convertWithPandoc($mdPath, $htmlPath); http_response_code(200); header('Content-Type: application/json'); echo json_encode([ 'status' => 'success', 'input' => $safeName, 'output' => 'html_output/' . $htmlName ]); } catch (Throwable $e) { http_response_code(500); header('Content-Type: application/json'); echo json_encode(['error' => $e->getMessage()]); }