feat: fix file deletion on save + trash policy + documents/ prefix + relink browser

1. note_intention: Delete old file only when a genuinely new upload arrives
   (32-char hex file_id), not when the FilePond pool preserves an existing
   file by sending its DB integer ID.  Previously the DB integer ID
   triggered $hasNewNote=true, which deleted the existing note_intention
   from disk+DB, then handleFilePondSingleFile couldn't re-process it
   because the regex requires a hex pattern.  Same fix applied to cover.

2. All file deletions now use deleteThesisFileToTrash() which renames
   files to tmp/_trash/ instead of unlinking.  The trash preserves
   original filenames prefixed with DB id for traceability.  Skips
   website URLs and PeerTube refs (no disk file).

3. Storage prefix changed from theses/ to documents/ to reflect that
   the folder holds all document types (determined by file_type in DB).
   MediaController visibility gate supports both prefixes for backward
   compat with existing files.

4. File browser + relink feature for orphaned files:
   - /admin/fragments/file-browser.php — HTMX tree browser for
     storage/documents/ and storage/theses/
   - /admin/actions/filepond/relink.php — POST endpoint that inserts
     a thesis_files row pointing to existing on-disk file
   - Per-pool "📂 Relier" buttons (edit mode only)
   - JS: XamxamOpenFileBrowser / XamxamRelinkFile with FilePond integration
   - CSS: .relink-modal dialog + .file-browser tree styles
This commit is contained in:
Pontoporeia
2026-05-13 14:58:15 +02:00
parent 6f7a02244f
commit 79eddf5d5a
30 changed files with 191580 additions and 187 deletions

View File

@@ -38,7 +38,15 @@ switch ($action) {
$validObjet = ['tfe', 'thèse', 'frart'];
$selected = is_array($objetRaw) ? array_intersect($objetRaw, $validObjet) : [];
$objetRestriction = !empty($selected) ? implode(',', $selected) : 'tfe';
$link = $shareLink->create(1, $expiresAt, $objetRestriction, $name);
$lockedYearRaw = $_POST['locked_year'] ?? null;
$lockedYear = null;
if ($lockedYearRaw !== null && $lockedYearRaw !== '') {
$lockedYear = filter_var($lockedYearRaw, FILTER_VALIDATE_INT);
if ($lockedYear === false || $lockedYear < 2000 || $lockedYear > ((int)date('Y') + 3)) {
$lockedYear = null;
}
}
$link = $shareLink->create(1, $expiresAt, $objetRestriction, $name, $lockedYear);
$logger->logLinkCreate(
$link['slug'] ?? '',
true, // Always has password
@@ -86,7 +94,13 @@ switch ($action) {
if ($id > 0) {
$name = isset($_POST['name']) ? trim($_POST['name']) : null;
$expiresRaw = isset($_POST['expires_at']) ? trim($_POST['expires_at']) : null;
$shareLink->update($id, $name, $expiresRaw);
// locked_year: null=not sent (keep), ""=clear, otherwise year string
$lockedYearRaw = $_POST['locked_year'] ?? null;
$lockedYear = null; // default: not sent → don't change
if ($lockedYearRaw !== null) {
$lockedYear = $lockedYearRaw; // pass through: "" for clear, "2026" for set
}
$shareLink->update($id, $name, $expiresRaw, $lockedYear);
App::redirect('/admin/acces.php', success: 'Lien mis à jour.');
} else {
App::redirect('/admin/acces.php', error: 'Lien introuvable.');

View File

@@ -0,0 +1,120 @@
<?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();
// CSRF via header
$csrfHeader = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
if (!isset($_SESSION['csrf_token'])
|| !hash_equals($_SESSION['csrf_token'], $csrfHeader)) {
http_response_code(403);
die('Token CSRF invalide.');
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
die('Méthode non autorisée.');
}
$body = json_decode(file_get_contents('php://input'), true);
if (!is_array($body)) {
http_response_code(400);
die('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 === '') {
http_response_code(400);
die('Paramètres invalides (thesis_id + file_path requis).');
}
// Security: only allow paths under documents/ or theses/
if (!preg_match('#^(documents|theses)/#', $filePath)) {
http_response_code(403);
die('Chemin de fichier non autorisé.');
}
$absPath = STORAGE_ROOT . '/' . $filePath;
$realPath = realpath($absPath);
$realStorage = realpath(STORAGE_ROOT);
if ($realPath === false || !str_starts_with($realPath, $realStorage)) {
http_response_code(404);
die('Fichier introuvable ou chemin interdit.');
}
if (!is_file($realPath)) {
http_response_code(404);
die('Le chemin ne pointe pas vers un fichier.');
}
// Detect MIME if not provided
if ($mimeType === 'application/octet-stream') {
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($realPath);
}
// 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()) {
http_response_code(409);
die('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;

View File

@@ -55,7 +55,7 @@ function wasSelected($key, $value) {
$isAdmin = true;
$bodyClass = 'admin-body';
$extraCss = ['/assets/css/form.css', '/assets/css/filepond.min.css', '/assets/css/filepond-plugin-image-preview.min.css'];
$extraJs = ['/assets/js/vendor/filepond.min.js', '/assets/js/vendor/filepond-plugin-file-validate-type.min.js', '/assets/js/vendor/filepond-plugin-file-validate-size.min.js', '/assets/js/vendor/filepond-plugin-image-preview.min.js', '/assets/js/vendor/filepond-plugin-image-exif-orientation.min.js', '/assets/js/app/file-upload-filepond.js', '/assets/js/app/beforeunload-guard.js', '/assets/js/app/pill-search.js'];
$extraJs = ['/assets/js/vendor/filepond.min.js', '/assets/js/vendor/filepond-plugin-file-validate-type.min.js', '/assets/js/vendor/filepond-plugin-file-validate-size.min.js', '/assets/js/vendor/filepond-plugin-image-preview.min.js', '/assets/js/vendor/filepond-plugin-image-exif-orientation.min.js', '/assets/js/app/file-upload-filepond.js', '/assets/js/app/beforeunload-guard.js', '/assets/js/app/pill-search.js', '/assets/js/app/jury-autocomplete.js'];
require_once APP_ROOT . '/templates/head.php';
include APP_ROOT . '/templates/header.php';
include APP_ROOT . '/templates/admin/add.php';

View File

@@ -40,7 +40,7 @@ try {
$isAdmin = true; $bodyClass = 'admin-body';
$extraCss = ['/assets/css/form.css', '/assets/css/filepond.min.css', '/assets/css/filepond-plugin-image-preview.min.css'];
$extraJs = ['/assets/js/vendor/filepond.min.js', '/assets/js/vendor/filepond-plugin-file-validate-type.min.js', '/assets/js/vendor/filepond-plugin-file-validate-size.min.js', '/assets/js/vendor/filepond-plugin-image-preview.min.js', '/assets/js/vendor/filepond-plugin-image-exif-orientation.min.js', '/assets/js/app/file-upload-filepond.js', '/assets/js/app/beforeunload-guard.js', '/assets/js/app/pill-search.js'];
$extraJs = ['/assets/js/vendor/filepond.min.js', '/assets/js/vendor/filepond-plugin-file-validate-type.min.js', '/assets/js/vendor/filepond-plugin-file-validate-size.min.js', '/assets/js/vendor/filepond-plugin-image-preview.min.js', '/assets/js/vendor/filepond-plugin-image-exif-orientation.min.js', '/assets/js/app/file-upload-filepond.js', '/assets/js/app/beforeunload-guard.js', '/assets/js/app/pill-search.js', '/assets/js/app/jury-autocomplete.js'];
require_once APP_ROOT . '/templates/head.php';
include APP_ROOT . '/templates/header.php';
include APP_ROOT . '/templates/admin/edit.php';

View File

@@ -0,0 +1,146 @@
<?php
/**
* File browser fragment — returns a clickable directory tree of documents/ + theses/.
*
* GET /admin/fragments/file-browser.php?dir=documents/2025
*
* Used by the relink modal to let admins pick an orphaned file and reattach
* it to a thesis entry.
*/
require_once __DIR__ . '/../../../bootstrap.php';
require_once __DIR__ . '/../../../src/AdminAuth.php';
AdminAuth::requireLogin();
$storageRoot = STORAGE_ROOT;
// Determine which directory to browse
$relDir = trim($_GET['dir'] ?? '', '/');
if ($relDir !== '' && !preg_match('#^(documents|theses)/#', $relDir)) {
$relDir = '';
}
$currentAbs = $storageRoot . '/' . ($relDir !== '' ? $relDir . '/' : '');
// Security: prevent escaping STORAGE_ROOT
$realCurrent = realpath($currentAbs);
$realStorage = realpath($storageRoot);
if ($realCurrent === false || !str_starts_with($realCurrent, $realStorage)) {
http_response_code(403);
die('Chemin interdit.');
}
// Build breadcrumb
$breadcrumb = [];
if ($relDir !== '') {
$parts = explode('/', $relDir);
$accum = '';
foreach ($parts as $p) {
$accum = ltrim($accum . '/' . $p, '/');
$breadcrumb[] = ['label' => $p, 'dir' => $accum];
}
}
// Gather entries
$entries = [];
if (is_dir($realCurrent)) {
$dh = opendir($realCurrent);
if ($dh) {
while (($name = readdir($dh)) !== false) {
if ($name === '.' || $name === '..') continue;
$full = $realCurrent . '/' . $name;
$isDir = is_dir($full);
$entries[] = [
'name' => $name,
'is_dir' => $isDir,
'size' => $isDir ? null : filesize($full),
'ext' => $isDir ? null : strtolower(pathinfo($name, PATHINFO_EXTENSION)),
];
}
closedir($dh);
}
}
// Sort: dirs first, then files, alphabetical
usort($entries, function ($a, $b) {
if ($a['is_dir'] !== $b['is_dir']) return $a['is_dir'] ? -1 : 1;
return strnatcasecmp($a['name'], $b['name']);
});
// Human-readable filesize
function fmtSize(?int $bytes): string {
if ($bytes === null) return '';
if ($bytes >= 1_000_000_000) return round($bytes / 1_000_000_000, 1) . ' GB';
if ($bytes >= 1_000_000) return round($bytes / 1_000_000, 1) . ' MB';
if ($bytes >= 1_000) return round($bytes / 1_000, 1) . ' KB';
return $bytes . ' B';
}
// Determine parent dir
$parentDir = '';
if ($relDir !== '') {
$parentParts = explode('/', $relDir);
array_pop($parentParts);
$parentDir = implode('/', $parentParts);
}
$rootDirs = ['documents', 'theses'];
?>
<div id="file-browser-container" class="file-browser">
<?php if ($relDir === ''): ?>
<!-- Root: show top-level directories -->
<p class="file-browser-hint">Sélectionnez un dossier pour parcourir les fichiers orphelins.</p>
<ul class="file-browser-list">
<?php foreach ($rootDirs as $rd): ?>
<?php $rdAbs = $storageRoot . '/' . $rd; ?>
<li class="file-browser-entry file-browser-dir">
<a href="#" hx-get="/admin/fragments/file-browser.php?dir=<?= urlencode($rd) ?>"
hx-target="#file-browser-container" hx-swap="outerHTML">
<span class="file-browser-icon">📁</span>
<span class="file-browser-name"><?= htmlspecialchars($rd) ?>/</span>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<!-- Subdirectory: breadcrumb + entries -->
<nav class="file-browser-breadcrumb">
<a href="#" hx-get="/admin/fragments/file-browser.php"
hx-target="#file-browser-container" hx-swap="outerHTML">📂 racine</a>
<?php foreach ($breadcrumb as $i => $bc): ?>
<span class="file-browser-sep">/</span>
<a href="#" hx-get="/admin/fragments/file-browser.php?dir=<?= urlencode($bc['dir']) ?>"
hx-target="#file-browser-container" hx-swap="outerHTML"><?= htmlspecialchars($bc['label']) ?></a>
<?php endforeach; ?>
</nav>
<?php if (empty($entries)): ?>
<p class="file-browser-empty">Ce dossier est vide.</p>
<?php else: ?>
<ul class="file-browser-list">
<?php foreach ($entries as $e): ?>
<?php if ($e['is_dir']): ?>
<li class="file-browser-entry file-browser-dir">
<a href="#" hx-get="/admin/fragments/file-browser.php?dir=<?= urlencode($relDir . '/' . $e['name']) ?>"
hx-target="#file-browser-container" hx-swap="outerHTML">
<span class="file-browser-icon">📁</span>
<span class="file-browser-name"><?= htmlspecialchars($e['name']) ?>/</span>
</a>
</li>
<?php else: ?>
<li class="file-browser-entry file-browser-file"
data-file-path="<?= htmlspecialchars($relDir . '/' . $e['name']) ?>"
data-file-name="<?= htmlspecialchars($e['name']) ?>"
data-file-ext="<?= htmlspecialchars($e['ext'] ?? '') ?>"
data-file-size="<?= (int)($e['size'] ?? 0) ?>">
<button type="button" class="file-browser-select-btn"
onclick="XamxamRelinkFile(this)">
<span class="file-browser-icon">📄</span>
<span class="file-browser-name"><?= htmlspecialchars($e['name']) ?></span>
<span class="file-browser-size"><?= htmlspecialchars(fmtSize($e['size'])) ?></span>
</button>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php endif; ?>
</div>

View File

@@ -0,0 +1,10 @@
<?php
/**
* Admin fragment: generic pill-search (HTMX partial).
*/
require_once __DIR__ . '/../../../bootstrap.php';
require_once __DIR__ . '/../../../src/AdminAuth.php';
AdminAuth::requireLogin();
App::boot();
require_once APP_ROOT . '/public/partage/pill-search-fragment.php';