<?php
// Ensure compatibility across PHP versions
if (version_compare(PHP_VERSION, '5.6.0', '<')) {
    exit('This script requires PHP 5.6 or higher.');
}

// Only authenticated editors may download submission attachments.
require_once __DIR__ . '/checklogin.php';

// Validate and sanitize the filename from the query parameter
if (isset($_GET['filename'])) {
    // Break the filename using '____' as the separator
    $filename_parts = explode('____', $_GET['filename']);

    // Basic security check: Ensure that the filename conforms to expected patterns
    if (count($filename_parts) !== 2 || preg_match('/[^A-Za-z0-9_\-\.]/', $filename_parts[1])) {
        exit('Invalid filename');
    }

    // Set the sanitized filename
    $sanitized_filename = htmlspecialchars(basename($filename_parts[1]), ENT_QUOTES, 'UTF-8');

    // Set the path to the file (adjust based on your server setup)
    $file_path = realpath(__DIR__ . '/../attachments/' . $filename_parts[0] . '____' . $sanitized_filename);

    // Ensure that the file exists and is within the allowed directory
    if ($file_path && file_exists($file_path) && strpos($file_path, realpath(__DIR__ . '/../attachments/')) === 0) {
        // Clean output buffer and prevent any unnecessary data from being sent
        if (ob_get_level()) {
            ob_clean();
        }
        flush();

        // Set headers to force download
        header("Content-Type: application/octet-stream");
        header("Content-Disposition: attachment; filename=\"$sanitized_filename\"");
        header("Content-Length: " . filesize($file_path));

        // Output the file
        readfile($file_path);
        exit;
    } else {
        exit('File not found or invalid.');
    }
} else {
    exit('No filename provided.');
}
?>
