Files
zibo-dashboard/public/userarea/manutenzioni/ajax/download_file.php
T
2026-08-12 21:29:55 +03:00

73 lines
2.0 KiB
PHP

<?php
/**
* Serves an attachment. The attachments/ folder itself is closed by
* .htaccess — this is the only way to read a file, and it requires a
* logged-in session.
*
* scope = equipment | maintenance | intervention | signature
*/
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (empty($_SESSION['iduserlogin'])) {
http_response_code(401);
exit('Non autorizzato.');
}
require_once __DIR__ . '/../include/functions.php';
$scope = (string)($_GET['scope'] ?? 'equipment');
$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
http_response_code(400);
exit('ID non valido.');
}
$tables = [
'equipment' => 'inv_equipment_files',
'maintenance' => 'maint_maintenance_files',
'intervention' => 'maint_intervention_files',
];
$pdo = mnt_pdo();
if ($scope === 'signature') {
$stmt = $pdo->prepare("SELECT signature_path AS stored_name, 'firma.png' AS original_name, 'image/png' AS mime_type FROM maint_interventions WHERE id = ?");
$stmt->execute([$id]);
} elseif (isset($tables[$scope])) {
$stmt = $pdo->prepare("SELECT stored_name, original_name, mime_type FROM {$tables[$scope]} WHERE id = ?");
$stmt->execute([$id]);
} else {
http_response_code(400);
exit('Scope non valido.');
}
$file = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$file || empty($file['stored_name'])) {
http_response_code(404);
exit('File non trovato.');
}
// basename() keeps a crafted stored_name from escaping the folder
$path = __DIR__ . '/../attachments/' . basename((string)$file['stored_name']);
if (!is_file($path)) {
http_response_code(404);
exit('File non presente sul server.');
}
$mimeType = $file['mime_type'] ?: 'application/octet-stream';
$disposition = isset($_GET['download']) ? 'attachment' : 'inline';
header('Content-Type: ' . $mimeType);
header('Content-Length: ' . filesize($path));
header('Content-Disposition: ' . $disposition . '; filename="' . rawurlencode((string)$file['original_name']) . '"');
header('X-Content-Type-Options: nosniff');
readfile($path);