Files
xamxam/app/public/admin/actions/filepond/relink.php
Pontoporeia d588ae004d Reintroduce TFE duration metadata: DB columns, form fields, controllers, views, and migration
Add 'unsafe-eval' to CSP script-src directives (htmx requires Function())
2026-06-15 15:56:52 +02:00

125 lines
3.9 KiB
PHP

<?php
/**
* Relink endpoint — attach an orphaned on-disk file to a thesis.
*
* POST /admin/actions/filepond/relink.php
* Body: JSON { thesis_id: 123, file_path: "documents/2025/FOLDER/file.pdf",
* file_name: "file.pdf", file_size: 12345, mime_type: "application/pdf",
* queue_type: "tfe", file_type: "main" }
*
* Inserts a thesis_files row pointing to the existing on-disk file.
* The file is NOT copied or moved — it stays where it is.
*/
require_once __DIR__ . '/../../../../bootstrap.php';
require_once __DIR__ . '/../../../../src/AdminAuth.php';
AdminAuth::requireLogin();
// Always return JSON, even on errors
function relinkError(int $code, string $message): never {
http_response_code($code);
header('Content-Type: application/json');
echo json_encode(['ok' => false, 'error' => $message]);
exit;
}
// CSRF via header
$csrfHeader = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
if (!isset($_SESSION['csrf_token'])
|| !hash_equals($_SESSION['csrf_token'], $csrfHeader)) {
relinkError(403, 'Token CSRF invalide.');
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
relinkError(405, 'Méthode non autorisée.');
}
$body = json_decode(file_get_contents('php://input'), true);
if (!is_array($body)) {
relinkError(400, 'JSON invalide.');
}
$thesisId = filter_var($body['thesis_id'] ?? '', FILTER_VALIDATE_INT);
$filePath = trim($body['file_path'] ?? '');
$fileName = trim($body['file_name'] ?? basename($filePath));
$fileSize = (int)($body['file_size'] ?? 0);
$fileType = trim($body['file_type'] ?? '');
$queueType = trim($body['queue_type'] ?? '');
$mimeType = trim($body['mime_type'] ?? 'application/octet-stream');
if (!$thesisId || $filePath === '') {
relinkError(400, 'Paramètres invalides (thesis_id + file_path requis).');
}
// Security: only allow paths under tfe/ these/ frart/ documents/ or theses/
if (!preg_match('#^(tfe|these|frart|documents|theses)/#', $filePath)) {
relinkError(403, 'Chemin de fichier non autorisé.');
}
$absPath = STORAGE_ROOT . '/' . $filePath;
$realPath = realpath($absPath);
$realStorage = realpath(STORAGE_ROOT);
if ($realPath === false || !str_starts_with($realPath, $realStorage)) {
error_log('[relink] FILE NOT FOUND | absPath=' . $absPath . ' | realPath=' . var_export($realPath, true) . ' | realStorage=' . $realStorage);
relinkError(404, 'Fichier introuvable ou chemin interdit.');
}
if (!is_file($realPath)) {
relinkError(404, 'Le chemin ne pointe pas vers un fichier.');
}
// Detect MIME if not provided
if ($mimeType === 'application/octet-stream' && class_exists('finfo')) {
$finfo = new finfo(FILEINFO_MIME_TYPE);
$detected = $finfo->file($realPath);
if ($detected !== false && $detected !== '') {
$mimeType = $detected;
}
}
// Map queue_type to file_type if not explicitly given
if ($fileType === '') {
$fileTypeMap = [
'cover' => 'cover',
'note_intention' => 'note_intention',
'tfe' => 'main',
'annexe' => 'annex',
];
$fileType = $fileTypeMap[$queueType] ?? 'main';
}
require_once APP_ROOT . '/src/Database.php';
$db = Database::getInstance();
// Check if this file is already linked to this thesis (avoid duplicate)
$pdo = $db->getConnection();
$stmt = $pdo->prepare('SELECT id FROM thesis_files WHERE thesis_id = ? AND file_path = ?');
$stmt->execute([$thesisId, $filePath]);
if ($stmt->fetch()) {
relinkError(409, 'Ce fichier est déjà lié à ce TFE.');
}
$db->insertThesisFile(
$thesisId,
$fileType,
$filePath,
$fileName,
$fileSize,
$mimeType,
null,
null
);
// Get the new file's ID
$newId = $pdo->lastInsertId();
error_log("[relink] thesis_id=$thesisId file_path=$filePath file_type=$fileType new_id=$newId");
header('Content-Type: application/json');
echo json_encode([
'ok' => true,
'id' => (int)$newId,
'message' => 'Fichier relié avec succès.',
]);
exit;