prepare('SELECT * FROM doc_storage WHERE id = ? LIMIT 1'); $stmt->execute([$id]); $file = $stmt->fetch(); if (!$file) { json_error(404, 'File not found'); } // Access check: home file or owner file. $allowed = false; if (!empty($file['idhome'])) { $allowed = user_can_access_home($pdo, $user, (int) $file['idhome']); $baseDir = $config['homedocs_dir']; } elseif (!empty($file['owner_id'])) { $allowed = user_owns_owner($pdo, $user, (int) $file['owner_id']); $baseDir = $config['persondocs_dir']; } if (!$allowed) { json_error(403, 'No access to this file'); } $path = ($baseDir ?? '') . '/' . basename((string) $file['filename']); if (!is_file($path)) { json_error(404, 'File missing on disk'); } // Serve the binary file (override bootstrap JSON header). header('Content-Type: ' . (mime_content_type($path) ?: 'application/octet-stream')); header('Content-Disposition: attachment; filename="' . basename((string) $file['filename']) . '"'); header('Content-Length: ' . filesize($path)); readfile($path); exit;