Clean up this php code and add any recommended security enhancements.

<?php
// Include Parsedown and YAML parser
include_once 'includes/Parsedown.php';
include_once 'includes/YAMLParser.php';

$posts_dir = 'posts/';
$posts_per_page = 5;

// Get all Markdown files from the posts directory
$all_files = glob($posts_dir . '*.md');

/**
 * Function to extract the date from the YAML front matter
 *
 * @param string $file Path to the Markdown file
 * @return DateTime|null Date object or null if date is invalid or not found
 */
function getPostDate($file) {
    $content = file_get_contents($file);
    $content = str_replace("\r\n", "\n", $content); // Normalize line endings

    // Separate YAML front matter and Markdown content
    if (preg_match('/^---(.*?)---/s', $content, $matches)) {
        $yaml_content = trim($matches[1]);
        $yaml = parseYAML($yaml_content);
        if (is_array($yaml) && isset($yaml['date'])) {
            $date = DateTime::createFromFormat('Y-m-d', $yaml['date']);
            if ($date) {
                return $date;
            }
        }
    }
    return null; // No valid date found
}

// Sort files by creation date from YAML front matter, newest first
usort($all_files, function($a, $b) {
    $dateA = getPostDate($a);
    $dateB = getPostDate($b);

    if ($dateA == $dateB) {
        return 0;
    }
    if ($dateA === null) {
        return 1; // Move posts without dates to the end
    }
    if ($dateB === null) {
        return -1;
    }

    // Compare timestamps instead of DateTime objects directly
    return $dateB->getTimestamp() <=> $dateA->getTimestamp(); // Sort in descending order
});

// Pagination
$total_posts = count($all_files);
$total_pages = max(ceil($total_posts / $posts_per_page), 1);

// Get current page from query parameter with validation
$current_page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, [
    'options' => [
        'default'   => 1,
        'min_range' => 1,
        'max_range' => $total_pages,
    ],
]);

// Calculate the offset
$offset = ($current_page - 1) * $posts_per_page;

// Slice the array of files for the current page
$files = array_slice($all_files, $offset, $posts_per_page);

// Instantiate Parsedown and enable safe mode to prevent XSS
$parsedown = new Parsedown();
$parsedown->setSafeMode(true);

// Include the header
include 'header.php';

// Display posts
foreach ($files as $file) {
    $content = file_get_contents($file);
    $content = str_replace("\r\n", "\n", $content); // Normalize line endings

    // Separate YAML front matter and Markdown content
    if (preg_match('/^---(.*?)---(.*)/s', $content, $matches)) {
        $yaml_content = trim($matches[1]);
        $yaml = parseYAML($yaml_content);
        $md_content = trim($matches[2]);
    } else {
        $yaml = [];
        $md_content = $content;
    }

    // Ensure $yaml is an array
    if (!is_array($yaml)) {
        $yaml = [];
    }

    // Extract the content before the readmore tag
    $content_parts = explode('<!--more-->', $md_content);
    $intro = $content_parts[0];

    // Parse Markdown
    $html_intro = $parsedown->text($intro);

    // Display the post
    echo '<div class="post">';
    $title = htmlspecialchars($yaml['title'] ?? 'Untitled', ENT_QUOTES, 'UTF-8');
    $basename = htmlspecialchars(basename($file), ENT_QUOTES, 'UTF-8');
    echo '<h2><a href="post.php?file=' . urlencode($basename) . '">' . $title . '</a></h2>';

    if (!empty($yaml['date'])) {
        $date = DateTime::createFromFormat('Y-m-d', $yaml['date']);
        if ($date) {
            echo '<p class="date">' . htmlspecialchars($date->format('F j, Y'), ENT_QUOTES, 'UTF-8') . '</p>';
        }
    }

    echo $html_intro;
    if (count($content_parts) > 1) {
        // There's more content after the readmore tag
        echo '<p><a href="post.php?file=' . urlencode($basename) . '">Read more...</a></p>';
    }
    echo '</div>';
}

// Pagination controls
echo '<div class="pagination">';
if ($current_page > 1) {
    echo '<a href="?page=' . ($current_page - 1) . '">Previous</a> ';
}
for ($i = 1; $i <= $total_pages; $i++) {
    if ($i == $current_page) {
        echo '<span class="current-page">' . $i . '</span> ';
    } else {
        echo '<a href="?page=' . $i . '">' . $i . '</a> ';
}
}
if ($current_page < $total_pages) {
    echo '<a href="?page=' . ($current_page + 1) . '">Next</a>';
}
echo '</div>';

// Include the footer
include 'footer.php';
?>