35311-vm/download_document.php
2025-10-30 00:12:08 +00:00

66 lines
1.7 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
if (!isset($_SESSION['user_id'])) {
header("HTTP/1.1 403 Forbidden");
exit("Access denied.");
}
$document_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($document_id === 0) {
header("HTTP/1.1 404 Not Found");
exit;
}
$pdo = db();
// Fetch document details
$stmt = $pdo->prepare("SELECT * FROM documents WHERE id = ?");
$stmt->execute([$document_id]);
$document = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$document) {
header("HTTP/1.1 404 Not Found");
exit;
}
// Permission check
$user_role = $_SESSION['user_role'];
$user_id = $_SESSION['user_id'];
$has_permission = false;
if ($user_role === 'staff') {
$has_permission = true;
} elseif ($user_role === 'partner') {
$stmt = $pdo->prepare("SELECT id FROM partners WHERE user_id = ?");
$stmt->execute([$user_id]);
$partner_id = $stmt->fetchColumn();
if ($partner_id && $document['partner_id'] == $partner_id) {
$has_permission = true;
}
}
if (!$has_permission) {
header("HTTP/1.1 403 Forbidden");
exit("You do not have permission to access this file.");
}
// Serve the file for download
$file_path = $document['file_path'];
if (file_exists($file_path)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($document['file_name']) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
} else {
header("HTTP/1.1 404 Not Found");
exit("File not found on server.");
}