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;