76 lines
2.3 KiB
PHP
76 lines
2.3 KiB
PHP
<?php
|
|
|
|
$tokenRec = require_valid_token();
|
|
$token = $tokenRec['_token'];
|
|
|
|
if ($method !== 'GET') {
|
|
json_error('METHOD_NOT_ALLOWED', 'Method not allowed', 405);
|
|
}
|
|
|
|
$dbPath = QDB_PATH;
|
|
if (!file_exists($dbPath)) {
|
|
json_error('NOT_FOUND', 'Database not found', 404);
|
|
}
|
|
|
|
$encMaster = file_get_contents($dbPath);
|
|
if ($encMaster === false) {
|
|
json_error('SERVER_ERROR', 'Could not read database', 500);
|
|
}
|
|
|
|
try {
|
|
$masterKey = get_master_key_bytes();
|
|
$plain = aes256_cbc_decrypt_bytes($encMaster, $masterKey);
|
|
} catch (QdbHttpResponse $e) {
|
|
throw $e;
|
|
} catch (Throwable $e) {
|
|
error_log($e->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;
|