Files
casadoc/public/userportal/api/documents-download.php
T
2026-07-27 21:04:07 +03:00

86 lines
2.9 KiB
PHP

<?php
require __DIR__ . '/_bootstrap.php';
/**
* @OA\Get(
* path="/documents-download.php",
* tags={"Documents"},
* summary="ZIP of uploaded home documents",
* description="Owner gets all files; share recipient gets only allowed sections.",
* security={{"bearerAuth":{}}},
* @OA\Parameter(name="idhome", in="query", required=true, @OA\Schema(type="integer")),
* @OA\Response(response=200, description="ZIP",
* @OA\MediaType(mediaType="application/zip", @OA\Schema(type="string", format="binary"))),
* @OA\Response(response=403, ref="#/components/responses/Forbidden")
* )
*/
require_method('GET');
$user = require_auth($pdo);
$config = require __DIR__ . '/config.php';
$idhome = (int) query('idhome', 0);
if ($idhome <= 0) {
json_error(422, 'idhome is required');
}
if (!user_can_access_home($pdo, $user, $idhome)) {
json_error(403, 'No access to this home');
}
if (!class_exists('ZipArchive')) {
json_error(500, 'ZipArchive extension not available');
}
$isOwner = user_owns_home($pdo, $user, $idhome);
// Share recipient: restrict to allowed sections.
$allowedSections = null;
if (!$isOwner) {
$shareStmt = $pdo->prepare(
"SELECT shared_sections FROM home_sharing
WHERE idhome = ? AND (idshareduser = ? OR shared_email = ?) AND status = 'accepted'
LIMIT 1"
);
$shareStmt->execute([$idhome, $user['id'], $user['email']]);
$decoded = json_decode((string) $shareStmt->fetchColumn(), true);
$allowedSections = is_array($decoded) ? array_map('intval', $decoded) : [];
}
$sql = 'SELECT ds.filename, d.document_name, s.section_name, d.idsections
FROM doc_storage ds
JOIN documents d ON d.document_id = ds.document_id
LEFT JOIN sections s ON s.idsections = d.idsections
WHERE ds.idhome = ?';
$params = [$idhome];
if ($allowedSections !== null) {
if (!$allowedSections) {
json_error(403, 'No shared sections');
}
$in = implode(',', array_fill(0, count($allowedSections), '?'));
$sql .= " AND d.idsections IN ($in)";
$params = array_merge($params, $allowedSections);
}
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();
$zipPath = tempnam(sys_get_temp_dir(), 'casadoc_') . '.zip';
$zip = new ZipArchive();
if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
json_error(500, 'Cannot create archive');
}
foreach ($rows as $r) {
$path = $config['homedocs_dir'] . '/' . basename((string) $r['filename']);
if (is_file($path)) {
$folder = ($r['section_name'] ?: 'Senza sezione') . '/' . ($r['document_name'] ?: 'documento');
$zip->addFile($path, $folder . '/' . basename((string) $r['filename']));
}
}
$zip->close();
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="Documenti_' . $idhome . '.zip"');
header('Content-Length: ' . filesize($zipPath));
readfile($zipPath);
@unlink($zipPath);
exit;