Files
janis b69e603791
Deploy / deploy (push) Successful in 38s
adding download helper and viewer
2026-05-12 10:08:17 +02:00

54 lines
1.6 KiB
PHP

<?php
session_start();
$loggedin = isset($_SESSION['neptune_loggedin']) && $_SESSION['neptune_loggedin'] === true;
if (!$loggedin) {
http_response_code(401);
echo 'Unauthorized';
exit;
}
$file = $_GET['file'] ?? '';
$mode = $_GET['mode'] ?? 'download';
if (!$file || preg_match('/[^a-zA-Z0-9_\.\-]/', $file)) {
http_response_code(400);
echo 'Invalid file';
exit;
}
$path = '/var/www/uploads/' . basename($file);
if (!file_exists($path)) {
http_response_code(404);
echo 'File not found';
exit;
}
require_once __DIR__ . '/config/database.php';
$db = getDbConnection();
$stmt = $db->prepare("SELECT original_name, mime_type FROM file_attachments WHERE stored_name = ?");
$stmt->execute([basename($file)]);
$att = $stmt->fetch(PDO::FETCH_ASSOC);
$originalName = $att ? $att['original_name'] : basename($file);
$mimeType = $att && $att['mime_type'] ? $att['mime_type'] : mime_content_type($path);
$ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
$viewable = in_array($ext, ['txt', 'md', 'pdf', 'csv']);
if ($mode === 'view' && $viewable) {
header('Content-Disposition: inline; filename="' . $originalName . '"');
header('Content-Type: ' . $mimeType);
header('Content-Length: ' . filesize($path));
header('X-File-Name: ' . $originalName);
header('X-File-Viewable: 1');
readfile($path);
exit;
}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $originalName . '"');
header('Content-Length: ' . filesize($path));
header('Cache-Control: no-cache');
readfile($path);