getMessage()); json_error('SERVER_ERROR', 'Decryption failed', 500); } $role = $tokenRec['role'] ?? ''; if ($role !== 'admin') { $tmpFilter = tempnam(sys_get_temp_dir(), 'qdb_filt_'); file_put_contents($tmpFilter, $plain); try { $fpdo = new PDO("sqlite:$tmpFilter"); $fpdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $fpdo->exec("PRAGMA foreign_keys = OFF;"); [$clause, $params] = rbac_client_filter($tokenRec); $delStmt = $fpdo->prepare("DELETE FROM client WHERE NOT ($clause)"); foreach ($params as $k => $v) $delStmt->bindValue($k, $v); $delStmt->execute(); $fpdo->exec("DELETE FROM client_answer WHERE clientCode NOT IN (SELECT clientCode FROM client)"); $fpdo->exec("DELETE FROM completed_questionnaire WHERE clientCode NOT IN (SELECT clientCode FROM client)"); foreach (['users', 'admin', 'supervisor', 'coach'] as $tbl) { $fpdo->exec("DELETE FROM $tbl"); } $fpdo = null; $plain = file_get_contents($tmpFilter); } finally { @unlink($tmpFilter); } } $type = strtolower(trim($_GET['type'] ?? 'encrypted')); if ($type === 'plain') { header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="questionnaire_database.sqlite"'); header('Content-Length: ' . strlen($plain)); echo $plain; exit; } $sessionKey = hkdf_session_key_from_token($token); $out = aes256_cbc_encrypt_bytes($plain, $sessionKey); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="questionnaire_database"'); header('Content-Length: ' . strlen($out)); echo $out; exit;