Markdown Files
+ $directory = realpath($directory); + if ($directory === false || !is_dir($directory)) { + die("Invalid directory"); + } + + $files = glob($directory . '/*.md'); + + usort($files, function($a, $b) { + return filemtime($b) - filemtime($a); + }); + + $latestFiles = array_slice($files, 0, 5); + $olderFiles = array_slice($files, 5); + + $alert = ''; + if ($_SERVER['REQUEST_METHOD'] === 'POST') { + if (isset($_POST['action']) && isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) { + if ($_POST['action'] === 'create' || $_POST['action'] === 'edit') { + $date = date('Ymd'); + $filename = $date . '-' . preg_replace('/[^a-zA-Z0-9_-]/', '', $_POST['filename']) . '.md'; + $filepath = $directory . '/' . $filename; + + if (strpos(realpath(dirname($filepath)), $directory) !== 0) { + die("Invalid file path"); + } + + $content = strip_tags($_POST['content']); + file_put_contents($filepath, $content); + $_SESSION['alert'] = [ + 'type' => 'success', + 'message' => 'File ' . ($_POST['action'] === 'create' ? 'created' : 'updated') . ' successfully.' + ]; + } elseif ($_POST['action'] === 'delete') { + $filename = basename($_POST['filename']); + $filepath = $directory . '/' . $filename; + + if (strpos(realpath(dirname($filepath)), $directory) !== 0) { + die("Invalid file path"); + } + + if (is_file($filepath) && pathinfo($filepath, PATHINFO_EXTENSION) === 'md') { + unlink($filepath); + $_SESSION['alert'] = [ + 'type' => 'warning', + 'message' => 'File deleted successfully.' + ]; + } + } + } + header('Location: ' . $_SERVER['PHP_SELF']); + exit; + } + + $editFile = isset($_GET['edit']) ? basename($_GET['edit']) : null; + if ($editFile !== null && strpos($editFile, '..') !== false) { + $editFile = null; + } + + if (empty($_SESSION['csrf_token'])) { + $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); + } + + // Display alert from session if it exists + if (isset($_SESSION['alert'])) { + $alertType = $_SESSION['alert']['type']; + $alertMessage = $_SESSION['alert']['message']; + $alert = "-
-
-
- -
--
-
-
Markdown Files
+-
+
+
+ +
+-
+
+