fix: prevent file deletion on relink + restore button now visible + OOB-style in-place update

Two critical fixes:

1. Relink flow no longer destroys/recreates FilePond instances:
   The relink (XamxamRelinkFile) and PeerTube relink (XamxamRelinkPeerTube)
   previously refreshed the entire fichiers fragment via HTMX after
   pond.addFile(). This triggered destroyFilePondsIn on ALL pools, which
   could fire server.remove callbacks and move existing files to corbeille.
   Now just closes the modal — the file is already added to the pool in-place,
   and syncOrderInput creates the hidden form input.

2. Cleanup page « Corbeille (restaurable) » now actually shows files:
   _cleanup-stats-data.php previously classified trash files by checking if
   the thesis_files DB row still existed. But both deleteThesisFileToTrash
   and FilepondHandler::handleRemove DELETE the DB row. So ALL trash files
   appeared as `stale` (not restorable). Now uses the JSON sidecar file
   presence as the classification criterion — if the sidecar exists and is
   recent, the file is restorable regardless of DB row state.

Also removed unused DB query from _cleanup-stats-data.php.
This commit is contained in:
Pontoporeia
2026-07-10 16:29:04 +02:00
parent ed19e30cf0
commit 3cecee10c9
12 changed files with 587 additions and 73 deletions
File diff suppressed because one or more lines are too long
+6
View File
@@ -7,3 +7,9 @@
- [x] Fix PeerTube upload failure: PHP /tmp tmpfs too small for large video files - [x] Fix PeerTube upload failure: PHP /tmp tmpfs too small for large video files
- [x] Fix keyword word-breaking in repertoire.php: widen kw grid column, add white-space: nowrap - [x] Fix keyword word-breaking in repertoire.php: widen kw grid column, add white-space: nowrap
- [x] Fix licence.php TOC: restore `open` attribute on `<details class="toc">` (lost in vrxsstns, never restored by uuomvtvm fix) - [x] Fix licence.php TOC: restore `open` attribute on `<details class="toc">` (lost in vrxsstns, never restored by uuomvtvm fix)
- [x] Fix hasFilePondQueueData() missing peertube: prefix check → new PeerTube uploads silently lost on edit
- [x] Fix handleWebsiteUrl() in ThesisEditController unconditionally deleting website rows on every edit
- [x] Fix FilePond server.remove potentially triggering during HTMX fragment teardown
- [x] Add restore-from-corbeille functionality in cleanup page
- [x] Fix cleanup stats: use sidecar JSON for restorability classification (not DB row existence)
- [x] Remove destructive HTMX fragment refresh from relink flow (close modal only, pond.addFile in-place)
@@ -120,17 +120,12 @@ function getCleanupStats(): array
$db = new Database(); $db = new Database();
$pdo = $db->getPDO(); $pdo = $db->getPDO();
$existingFileIds = [];
$stmt = $pdo->query('SELECT id FROM thesis_files');
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$existingFileIds[(int)$row['id']] = true;
}
$trStaleCount = 0; $trStaleCount = 0;
$trStaleSize = 0; $trStaleSize = 0;
$trStaleFiles = []; $trStaleFiles = [];
$trActiveCount = 0; $trActiveCount = 0;
$trActiveSize = 0; $trActiveSize = 0;
$trActiveFiles = [];
if (is_dir($trashDir)) { if (is_dir($trashDir)) {
$items = @scandir($trashDir); $items = @scandir($trashDir);
@@ -139,6 +134,10 @@ function getCleanupStats(): array
if ($item === '.' || $item === '..') { if ($item === '.' || $item === '..') {
continue; continue;
} }
// Skip JSON sidecar files — they're listed alongside their parent.
if (str_ends_with($item, '.json')) {
continue;
}
$filePath = $trashDir . '/' . $item; $filePath = $trashDir . '/' . $item;
if (!is_file($filePath)) { if (!is_file($filePath)) {
continue; continue;
@@ -148,20 +147,37 @@ function getCleanupStats(): array
$mtime = filemtime($filePath); $mtime = filemtime($filePath);
$ageDays = (int)(($now - $mtime) / 86400); $ageDays = (int)(($now - $mtime) / 86400);
$stale = false; // Check for sidecar metadata — files with sidecars are restorable
// regardless of whether the thesis_files DB row still exists.
if (preg_match('/^(\d+)_/', $item, $m)) { $sidecarPath = $filePath . '.json';
$dbId = (int)$m[1]; $hasSidecar = file_exists($sidecarPath);
if (!isset($existingFileIds[$dbId])) { $sidecarData = null;
$stale = true; if ($hasSidecar) {
$sidecarData = json_decode(file_get_contents($sidecarPath), true);
if (!is_array($sidecarData)) {
$hasSidecar = false;
$sidecarData = null;
} }
} }
if (!$stale && $ageDays > ($maxAgeTrash / 86400)) { // Restorable = has a valid sidecar AND is younger than max age
$stale = true; $restorable = $hasSidecar && $ageDays <= ($maxAgeTrash / 86400);
}
if ($stale) { if ($restorable) {
$trActiveCount++;
$trActiveSize += $size;
$trActiveFiles[] = [
'name' => $item,
'size' => $size,
'human' => humanBytes($size),
'age_days' => $ageDays,
'has_sidecar' => true,
'thesis_id' => $sidecarData['thesis_id'] ?? null,
'file_type' => $sidecarData['file_type'] ?? '?',
'original_name' => $sidecarData['file_name'] ?? '',
'original_path' => $sidecarData['file_path'] ?? '',
];
} else {
$trStaleCount++; $trStaleCount++;
$trStaleSize += $size; $trStaleSize += $size;
$trStaleFiles[] = [ $trStaleFiles[] = [
@@ -170,9 +186,6 @@ function getCleanupStats(): array
'human' => humanBytes($size), 'human' => humanBytes($size),
'age_days' => $ageDays, 'age_days' => $ageDays,
]; ];
} else {
$trActiveCount++;
$trActiveSize += $size;
} }
} }
} }
@@ -193,5 +206,6 @@ function getCleanupStats(): array
'trash_active_count' => $trActiveCount, 'trash_active_count' => $trActiveCount,
'trash_active_size' => $trActiveSize, 'trash_active_size' => $trActiveSize,
'trash_active_human' => humanBytes($trActiveSize), 'trash_active_human' => humanBytes($trActiveSize),
'trash_active_files' => $trActiveFiles,
]; ];
} }
@@ -92,7 +92,7 @@ if ($trStale > 0) {
<?php endif; ?> <?php endif; ?>
<?php if ($trStale > 0): ?> <?php if ($trStale > 0): ?>
<h3 id="tmp-trash-heading">Corbeille <span class="n-meta"><?= htmlspecialchars($trMeta) ?></span></h3> <h3 id="tmp-trash-heading">Corbeille (à nettoyer) <span class="n-meta"><?= htmlspecialchars($trMeta) ?></span></h3>
<table class="n-table" aria-labelledby="tmp-trash-heading"> <table class="n-table" aria-labelledby="tmp-trash-heading">
<thead><tr><th width="1%"><input type="checkbox" onchange="cleanupToggleAll(this, 'trash')" title="Tout sélectionner"></th><th>Nom</th><th>Taille</th><th>Âge</th><th width="1%"></th></tr></thead> <thead><tr><th width="1%"><input type="checkbox" onchange="cleanupToggleAll(this, 'trash')" title="Tout sélectionner"></th><th>Nom</th><th>Taille</th><th>Âge</th><th width="1%"></th></tr></thead>
<tbody> <tbody>
@@ -120,9 +120,62 @@ if ($trStale > 0) {
</table> </table>
<?php endif; ?> <?php endif; ?>
<?php if ($fpActive > 0 || $trActive > 0): ?> <?php
$trActiveFiles = $d['trash_active_files'] ?? [];
if (!empty($trActiveFiles)):
$trActiveMeta = $trActive . ' fichier' . ($trActive > 1 ? 's' : '');
if ($trActive > 0) {
$trActiveMeta .= ' · ' . ($d['trash_active_human'] ?? '');
}
?>
<h3 id="tmp-trash-restore-heading">Corbeille (restaurable) <span class="n-meta"><?= htmlspecialchars($trActiveMeta) ?></span></h3>
<p style="font-size:0.85em;color:var(--text-secondary);margin:0 0 var(--space-sm)">
Fichiers récemment supprimés pour lesquels le TFE associé existe encore. Vous pouvez les restaurer ou les supprimer définitivement.
</p>
<table class="n-table" aria-labelledby="tmp-trash-restore-heading">
<thead><tr><th>Nom</th><th>Taille</th><th>Âge</th><th>Origine</th><th width="1%"></th></tr></thead>
<tbody>
<?php foreach ($trActiveFiles as $f): ?>
<tr>
<td><strong><?= htmlspecialchars($f['name']) ?></strong></td>
<td style="white-space:nowrap"><?= htmlspecialchars($f['human']) ?></td>
<td style="white-space:nowrap">~<?= (int)$f['age_days'] ?> j</td>
<td style="font-size:0.85em;color:var(--text-secondary)">
<?= $f['has_sidecar'] ? htmlspecialchars($f['original_name'] ?? '?') . ' (' . htmlspecialchars($f['file_type'] ?? '?') . ')' : 'métadonnées indisponibles' ?>
</td>
<td style="white-space:nowrap">
<?php if ($f['has_sidecar']): ?>
<button type="button" class="btn btn--sm"
style="font-size:0.85em;padding:2px var(--space-xs);margin-right:4px"
hx-post="/admin/actions/restore-trash.php"
hx-confirm="Restaurer ce fichier vers le TFE associé ?"
hx-vals='{"csrf_token":"<?= htmlspecialchars($_SESSION['csrf_token']) ?>","trash_file":"<?= htmlspecialchars($f['name']) ?>"}'
hx-target="#tmp-cleanup-stats-wrapper"
hx-swap="innerHTML"
hx-indicator="#tmp-cleanup-stats-wrapper">
↺ Restaurer
</button>
<?php endif; ?>
<button type="button" class="btn btn--sm btn--danger"
style="font-size:0.85em;padding:2px var(--space-xs)"
hx-post="/admin/actions/cleanup-tmp.php"
hx-confirm="Supprimer définitivement ce fichier de la corbeille ?"
hx-vals='{"csrf_token":"<?= htmlspecialchars($_SESSION['csrf_token']) ?>","trash_file":"<?= htmlspecialchars($f['name']) ?>"}'
hx-target="#tmp-cleanup-stats-wrapper"
hx-swap="innerHTML"
hx-indicator="#tmp-cleanup-stats-wrapper">
<?= icon('trash') ?>
Supprimer
</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<?php if ($fpActive > 0): ?>
<p style="margin:var(--space-sm) 0 0 0;font-size:0.85em;color:var(--text-secondary)">Conservés : <p style="margin:var(--space-sm) 0 0 0;font-size:0.85em;color:var(--text-secondary)">Conservés :
<?php if ($fpActive) echo $fpActive . ' téléversement(s) actif(s) (' . htmlspecialchars($d['filepond_active_human']) . '), '; ?> <?= $fpActive . ' téléversement(s) actif(s) (' . htmlspecialchars($d['filepond_active_human']) . ')' ?>
<?php if ($trActive) echo $trActive . ' fichier(s) récent(s) (' . htmlspecialchars($d['trash_active_human']) . ')'; ?>
</p> </p>
<?php endif; ?> <?php endif; ?>
+157
View File
@@ -0,0 +1,157 @@
<?php
/**
* Restore a trashed file back to its original location (admin).
*
* POST /admin/actions/restore-trash.php
* Body: trash_file=123_filename.pdf
*
* Reads the JSON sidecar file (trash_file.json) to get the original
* thesis_files row metadata, re-inserts the DB row, and moves the file
* back from tmp/_trash to its original storage path.
*/
require_once __DIR__ . '/../../../bootstrap.php';
require_once __DIR__ . '/../../../src/AdminAuth.php';
AdminAuth::requireLogin();
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'Méthode non autorisée.']);
exit;
}
if (!isset($_POST['csrf_token'], $_SESSION['csrf_token'])
|| !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
http_response_code(403);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'CSRF invalide.']);
exit;
}
$trashFile = trim($_POST['trash_file'] ?? '');
if ($trashFile === '') {
http_response_code(400);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'Nom de fichier invalide.']);
exit;
}
$storageRoot = STORAGE_ROOT;
$trashDir = $storageRoot . '/tmp/_trash';
$trashPath = $trashDir . '/' . basename($trashFile);
$sidecarPath = $trashPath . '.json';
// Validate the trash file is inside the trash directory
if (!is_file($trashPath) || !str_starts_with(realpath($trashPath), realpath($trashDir))) {
http_response_code(404);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'Fichier introuvable dans la corbeille.']);
exit;
}
// Read sidecar metadata
if (!file_exists($sidecarPath)) {
http_response_code(400);
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'ok' => false,
'error' => 'Métadonnées de restauration absentes (fichier trop ancien ?). Utilisez "Relier un fichier existant".',
]);
exit;
}
$sidecar = json_decode(file_get_contents($sidecarPath), true);
if (!is_array($sidecar) || empty($sidecar['file_path']) || empty($sidecar['thesis_id'])) {
http_response_code(400);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'Métadonnées corrompues.']);
exit;
}
$originalPath = $sidecar['file_path'];
$thesisId = (int)$sidecar['thesis_id'];
$fileType = $sidecar['file_type'] ?? 'other';
$fileName = $sidecar['file_name'] ?? basename($originalPath);
$mimeType = $sidecar['mime_type'] ?? 'application/octet-stream';
$fileSize = (int)($sidecar['file_size'] ?? 0);
$displayLabel = $sidecar['display_label'] ?? null;
// Verify the thesis still exists
require_once __DIR__ . '/../../../src/Database.php';
$db = new Database();
$thesis = $db->getThesis($thesisId);
if (!$thesis) {
http_response_code(404);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'Le TFE associé n\'existe plus.']);
exit;
}
// Check no file already exists at the original path
$absOriginal = $storageRoot . '/' . $originalPath;
if (file_exists($absOriginal)) {
// File already restored or a new file replaced it — just clean up the trash
@unlink($trashPath);
@unlink($sidecarPath);
http_response_code(409);
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'ok' => false,
'error' => 'Un fichier existe déjà à l\'emplacement d\'origine. Fichier corbeille nettoyé.',
]);
exit;
}
// Ensure parent directory exists
$parentDir = dirname($absOriginal);
if (!is_dir($parentDir)) {
mkdir($parentDir, 0755, true);
}
// Move file back from trash to original location
if (!rename($trashPath, $absOriginal)) {
http_response_code(500);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'Échec du déplacement du fichier.']);
exit;
}
chmod($absOriginal, 0644);
// Delete the sidecar file
@unlink($sidecarPath);
// Re-insert the thesis_files DB row
$db->insertThesisFile(
$thesisId,
$fileType,
$originalPath,
$fileName,
$fileSize,
$mimeType,
$displayLabel,
null
);
$newId = $db->getConnection()->lastInsertId();
error_log("[restore-trash] thesis_id=$thesisId file_id=$newId restored from trash: $trashFile$originalPath");
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
// HTMX request: re-render the fragment
if (isset($_SERVER['HTTP_HX_REQUEST'])) {
header('HX-Trigger: refreshStats');
require __DIR__ . '/cleanup-stats-fragment.php';
exit;
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'ok' => true,
'id' => $newId,
'thesis_id' => $thesisId,
'message' => 'Fichier restauré avec succès.',
]);
exit;
@@ -321,6 +321,15 @@
remove: (source, load, error) => { remove: (source, load, error) => {
console.log(`[filepond] remove called | id=${source}`); console.log(`[filepond] remove called | id=${source}`);
// During teardown (HTMX swap), skip server round-trips.
// FilePond 4.x destroy() does not normally fire remove callbacks,
// but this guard prevents accidental deletion of DB files as a
// defence-in-depth measure.
if (_xamxamTeardown) {
console.log(`[filepond] remove skipped (teardown) | id=${source}`);
load();
return;
}
// Hex IDs (32 chars) → temp files → use revert endpoint // Hex IDs (32 chars) → temp files → use revert endpoint
if (/^[a-f0-9]{32}$/.test(source)) { if (/^[a-f0-9]{32}$/.test(source)) {
fetch(`${base}/revert.php`, { fetch(`${base}/revert.php`, {
@@ -519,6 +528,13 @@
}); });
}; };
/**
* Guard flag set during destroyFilePondsIn — the server.remove callback
* checks this and skips the server round-trip during teardown to prevent
* accidental deletion of existing DB files from FilePond.destroy().
*/
let _xamxamTeardown = false;
/** /**
* Destroy FilePond instances inside a given container element. * Destroy FilePond instances inside a given container element.
* Generic: handles ANY HTMX swap target, not just known IDs. * Generic: handles ANY HTMX swap target, not just known IDs.
@@ -563,8 +579,12 @@
} catch (_abort) {} } catch (_abort) {}
} }
} }
_xamxamTeardown = true;
pond.destroy(); pond.destroy();
} catch (_) {} _xamxamTeardown = false;
} catch (_) {
_xamxamTeardown = false;
}
} }
}); });
} }
@@ -885,24 +905,9 @@
" | found=" + " | found=" +
!!input, !!input,
); );
var closeAndRefresh = () => { var closeModal = () => {
var modal = document.getElementById("relink-modal"); var modal = document.getElementById("relink-modal");
if (modal) modal.close(); if (modal) modal.close();
// Re-fetch the fichiers fragment from the server so the
// newly-linked file appears in the FilePond pools.
var block = document.getElementById("format-fichiers-block");
if (block && window.htmx) {
let url = "/admin/fragments/fichiers.php";
if (window.__xamxamRelinkCtx?.thesisId) {
url +=
"?_thesis_id=" +
encodeURIComponent(window.__xamxamRelinkCtx.thesisId);
}
htmx.ajax("GET", url, {
target: "#format-fichiers-block",
swap: "outerHTML",
});
}
}; };
if (input) { if (input) {
const pond = FilePond.find(input); const pond = FilePond.find(input);
@@ -924,25 +929,25 @@
" | queueType=" + " | queueType=" +
queueType, queueType,
); );
closeAndRefresh(); closeModal();
}) })
.catch((err) => { .catch((err) => {
console.error("[relink] addFile rejected", err); console.error("[relink] addFile rejected", err);
closeAndRefresh(); closeModal();
}); });
} else { } else {
console.error( console.error(
"[relink] FilePond.find returned null for input", "[relink] FilePond.find returned null for input",
input, input,
); );
closeAndRefresh(); closeModal();
} }
} else { } else {
console.warn( console.warn(
"[relink] input not found, page may have reloaded | queueType=" + "[relink] input not found, page may have reloaded | queueType=" +
queueType, queueType,
); );
closeAndRefresh(); closeModal();
} }
// Mark form dirty // Mark form dirty
@@ -1008,18 +1013,9 @@
var input = document.querySelector( var input = document.querySelector(
'.tfe-file-picker[data-queue-type="tfe"]', '.tfe-file-picker[data-queue-type="tfe"]',
); );
var closeAndRefresh = () => { var closeModal = () => {
var modal = document.getElementById("peertube-relink-modal"); var modal = document.getElementById("peertube-relink-modal");
if (modal) modal.close(); if (modal) modal.close();
var block = document.getElementById("format-fichiers-block");
if (block && window.htmx) {
var url = "/admin/fragments/fichiers.php";
if (thesisId) url += `?_thesis_id=${encodeURIComponent(thesisId)}`;
htmx.ajax("GET", url, {
target: "#format-fichiers-block",
swap: "outerHTML",
});
}
}; };
if (input) { if (input) {
var pond = FilePond.find(input); var pond = FilePond.find(input);
@@ -1035,19 +1031,19 @@
}) })
.then(() => { .then(() => {
console.log("[pt-relink] addFile resolved"); console.log("[pt-relink] addFile resolved");
closeAndRefresh(); closeModal();
}) })
.catch((err) => { .catch((err) => {
console.error("[pt-relink] addFile rejected", err); console.error("[pt-relink] addFile rejected", err);
closeAndRefresh(); closeModal();
}); });
} else { } else {
console.error("[pt-relink] FilePond.find returned null"); console.error("[pt-relink] FilePond.find returned null");
closeAndRefresh(); closeModal();
} }
} else { } else {
console.warn("[pt-relink] input not found"); console.warn("[pt-relink] input not found");
closeAndRefresh(); closeModal();
} }
window.__xamxamDirty = true; window.__xamxamDirty = true;
+28 -2
View File
@@ -627,15 +627,25 @@ class ThesisEditController
{ {
$websiteUrl = trim($post['website_url'] ?? ''); $websiteUrl = trim($post['website_url'] ?? '');
// Remove existing website rows (website URLs have no disk file) // Find existing website row (if any)
$existingFiles = $this->db->getThesisFiles($thesisId); $existingFiles = $this->db->getThesisFiles($thesisId);
$existingWebsiteRow = null;
foreach ($existingFiles as $f) { foreach ($existingFiles as $f) {
if ($f['file_type'] === 'website') { if ($f['file_type'] === 'website') {
$this->db->deleteThesisFile((int)$f['id'], $thesisId); $existingWebsiteRow = $f;
break;
} }
} }
// No URL provided and no existing row → nothing to do.
if ($websiteUrl === '' && $existingWebsiteRow === null) {
return;
}
// URL explicitly cleared → delete existing website row.
if ($websiteUrl === '') { if ($websiteUrl === '') {
$this->db->deleteThesisFile((int)$existingWebsiteRow['id'], $thesisId);
error_log('ThesisEditController: website removed (explicitly cleared)');
return; return;
} }
@@ -650,6 +660,21 @@ class ThesisEditController
$sortOrder = isset($post['website_order']) ? (int)$post['website_order'] : null; $sortOrder = isset($post['website_order']) ? (int)$post['website_order'] : null;
$fileName = rtrim(preg_replace('#^https?://#i', '', $websiteUrl), '/'); $fileName = rtrim(preg_replace('#^https?://#i', '', $websiteUrl), '/');
if ($existingWebsiteRow !== null) {
// Preserve existing label if no new label is provided.
if ($label === '' && !empty($existingWebsiteRow['display_label'])) {
$label = $existingWebsiteRow['display_label'];
}
// Update existing row in-place instead of delete + re-insert.
$this->db->updateThesisWebsiteUrl(
(int)$existingWebsiteRow['id'],
$thesisId,
$websiteUrl,
$fileName,
$label !== '' ? $label : null
);
error_log("ThesisEditController: website updated → $websiteUrl");
} else {
$this->db->insertThesisFile( $this->db->insertThesisFile(
$thesisId, $thesisId,
'website', 'website',
@@ -663,3 +688,4 @@ class ThesisEditController
error_log("ThesisEditController: website stored → $websiteUrl"); error_log("ThesisEditController: website stored → $websiteUrl");
} }
} }
}
+18 -1
View File
@@ -872,7 +872,9 @@ trait ThesisFileHandler
$ids = is_array($raw) ? $raw : [$raw]; $ids = is_array($raw) ? $raw : [$raw];
foreach ($ids as $id) { foreach ($ids as $id) {
$id = is_string($id) ? trim($id) : ''; $id = is_string($id) ? trim($id) : '';
if ($id !== '' && preg_match('/^[a-f0-9]{32}$/', $id)) { // 32-char hex IDs = regular FilePond async uploads.
// peertube: prefix = video/audio uploaded to PeerTube via process.php.
if ($id !== '' && (preg_match('/^[a-f0-9]{32}$/', $id) || str_starts_with($id, 'peertube:'))) {
return true; return true;
} }
} }
@@ -1299,6 +1301,21 @@ trait ThesisFileHandler
@copy($abs, $trashPath); @copy($abs, $trashPath);
@unlink($abs); @unlink($abs);
} }
// Save metadata sidecar for potential restore
$sidecar = [
'thesis_id' => $thesisId,
'file_id' => $fileId,
'file_type' => $fileRow['file_type'] ?? 'other',
'file_path' => $filePath,
'file_name' => $fileRow['file_name'] ?? basename($filePath),
'mime_type' => $fileRow['mime_type'] ?? 'application/octet-stream',
'file_size' => $fileRow['file_size'] ?? 0,
'deleted_at' => date('c'),
];
@file_put_contents(
$trashPath . '.json',
json_encode($sidecar, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
);
error_log("ThesisFileHandler: file {$fileId} moved to trash → {$trashName}"); error_log("ThesisFileHandler: file {$fileId} moved to trash → {$trashName}");
} }
} }
+19
View File
@@ -2565,6 +2565,25 @@ class Database
)->execute([$label ?: null, $fileId, $thesisId]); )->execute([$label ?: null, $fileId, $thesisId]);
} }
/**
* Update an existing website-type thesis_files row in-place.
*
* Avoids the delete-then-insert pattern that loses the row ID and
* any associated metadata. Only updates the URL, derived filename,
* and optional display label.
*/
public function updateThesisWebsiteUrl(
int $fileId,
int $thesisId,
string $url,
string $fileName,
?string $label
): void {
$this->pdo->prepare(
'UPDATE thesis_files SET file_path = ?, file_name = ?, display_label = ? WHERE id = ? AND thesis_id = ?'
)->execute([$url, $fileName, $label ?: null, $fileId, $thesisId]);
}
/** /**
* Delete a single thesis file record by its ID and optionally remove the * Delete a single thesis file record by its ID and optionally remove the
* file from disk. Returns the file_path that was deleted (or null if not * file from disk. Returns the file_path that was deleted (or null if not
+21
View File
@@ -332,6 +332,12 @@ class FilepondHandler
} }
$filePath = $fileRow['file_path'] ?? ''; $filePath = $fileRow['file_path'] ?? '';
$thesisId = $fileRow['thesis_id'] ?? 0;
$fileType = $fileRow['file_type'] ?? 'other';
$fileName = $fileRow['file_name'] ?? basename($filePath);
$mimeType = $fileRow['mime_type'] ?? 'application/octet-stream';
$fileSize = $fileRow['file_size'] ?? 0;
if ($filePath !== '' if ($filePath !== ''
&& !str_starts_with($filePath, 'peertube_ids:') && !str_starts_with($filePath, 'peertube_ids:')
&& !str_starts_with($filePath, 'http://') && !str_starts_with($filePath, 'http://')
@@ -345,6 +351,21 @@ class FilepondHandler
} }
$trashPath = $trashDir . '/' . $dbId . '_' . basename($filePath); $trashPath = $trashDir . '/' . $dbId . '_' . basename($filePath);
rename($absPath, $trashPath); rename($absPath, $trashPath);
// Save metadata sidecar for potential restore
$sidecar = [
'thesis_id' => (int)$thesisId,
'file_id' => $dbId,
'file_type' => $fileType,
'file_path' => $filePath,
'file_name' => $fileName,
'mime_type' => $mimeType,
'file_size' => (int)$fileSize,
'deleted_at' => date('c'),
];
@file_put_contents(
$trashPath . '.json',
json_encode($sidecar, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
);
} }
} }
+89
View File
@@ -38,6 +38,17 @@ class PureLogicTest extends TestCase
}; };
} }
/**
* Invoke the private hasFilePondQueueData() method via reflection.
* The method lives in the ThesisFileHandler trait, used by ThesisCreateController.
*/
private function invokeHasFilePondQueueData(array $post): bool
{
$ctrl = $this->getThesisCreateController();
$ref = new ReflectionMethod(ThesisCreateController::class, 'hasFilePondQueueData');
return $ref->invoke($ctrl, $post);
}
// ── splitJuryByRole ────────────────────────────────────────────────────── // ── splitJuryByRole ──────────────────────────────────────────────────────
public function testSplitJuryByRoleAllRoles(): void public function testSplitJuryByRoleAllRoles(): void
@@ -150,4 +161,82 @@ class PureLogicTest extends TestCase
$this->assertSame('image', $ctrl->exposedDetectFileType('application/octet-stream', 'webp')); $this->assertSame('image', $ctrl->exposedDetectFileType('application/octet-stream', 'webp'));
$this->assertSame('caption', $ctrl->exposedDetectFileType('application/octet-stream', 'vtt')); $this->assertSame('caption', $ctrl->exposedDetectFileType('application/octet-stream', 'vtt'));
} }
// ── hasFilePondQueueData ────────────────────────────────────────────────
public function testHasFilePondQueueDataReturnsTrueForHexId(): void
{
$post = ['queue_file' => ['tfe' => ['abc123def456abc123def456abc123de']]];
$this->assertTrue($this->invokeHasFilePondQueueData($post));
}
public function testHasFilePondQueueDataReturnsTrueForPeertubeVideo(): void
{
$post = ['queue_file' => ['tfe' => ['peertube:video:bmpQZTUPv4ou8ufiwajV63']]];
$this->assertTrue(
$this->invokeHasFilePondQueueData($post),
'peertube:video:UUID should be detected as FilePond data'
);
}
public function testHasFilePondQueueDataReturnsTrueForPeertubeAudio(): void
{
$post = ['queue_file' => ['tfe' => ['peertube:audio:xyz123']]];
$this->assertTrue(
$this->invokeHasFilePondQueueData($post),
'peertube:audio:UUID should be detected as FilePond data'
);
}
public function testHasFilePondQueueDataReturnsTrueForMixedIds(): void
{
$post = ['queue_file' => ['tfe' => ['123', 'peertube:video:abc123', '456']]];
$this->assertTrue(
$this->invokeHasFilePondQueueData($post),
'Mixed array containing a peertube: ID should be detected'
);
}
public function testHasFilePondQueueDataReturnsTrueForHexInCoverQueue(): void
{
$post = ['queue_file' => ['cover' => ['abcdef1234567890abcdef1234567890']]];
$this->assertTrue($this->invokeHasFilePondQueueData($post));
}
public function testHasFilePondQueueDataReturnsTrueForPeertubeInCoverQueue(): void
{
$post = ['queue_file' => ['cover' => ['peertube:video:uuid1']]];
$this->assertTrue($this->invokeHasFilePondQueueData($post));
}
public function testHasFilePondQueueDataReturnsFalseForNumericIdsOnly(): void
{
$post = ['queue_file' => ['tfe' => ['123', '456']]];
$this->assertFalse($this->invokeHasFilePondQueueData($post));
}
public function testHasFilePondQueueDataReturnsFalseForEmptyInput(): void
{
$this->assertFalse($this->invokeHasFilePondQueueData([]));
$this->assertFalse($this->invokeHasFilePondQueueData(['queue_file' => []]));
$this->assertFalse($this->invokeHasFilePondQueueData(['queue_file' => ['tfe' => []]]));
}
public function testHasFilePondQueueDataReturnsFalseForEmptyStrings(): void
{
$post = ['queue_file' => ['tfe' => ['', ' ']]];
$this->assertFalse($this->invokeHasFilePondQueueData($post));
}
public function testHasFilePondQueueDataHandlesScalarNotArray(): void
{
$post = ['queue_file' => ['tfe' => 'peertube:video:singleUuid']];
$this->assertTrue($this->invokeHasFilePondQueueData($post));
$post2 = ['queue_file' => ['tfe' => 'abc123def456abc123def456abc123de']];
$this->assertTrue($this->invokeHasFilePondQueueData($post2));
$post3 = ['queue_file' => ['tfe' => '123']];
$this->assertFalse($this->invokeHasFilePondQueueData($post3));
}
} }
+116
View File
@@ -193,4 +193,120 @@ class ThesisEditValidationTest extends TestCase
$file = $pdo->query("SELECT * FROM thesis_files WHERE thesis_id = $thesisId AND file_type = 'website'")->fetch(); $file = $pdo->query("SELECT * FROM thesis_files WHERE thesis_id = $thesisId AND file_type = 'website'")->fetch();
$this->assertStringContainsString('example.com/path', $file['file_name']); $this->assertStringContainsString('example.com/path', $file['file_name']);
} }
// ── handleWebsiteUrl regression: existing rows preserved (not deleted-then-recreated) ─
public function testHandleWebsiteUrlPreservesExistingRowWhenUrlUnchanged(): void
{
[$authorId, $thesisId] = TestDatabase::seedBasicThesis('Keep Site', 'Author', 2024);
$pdo = TestDatabase::getPDO();
// Seed an existing website row
$pdo->prepare(
"INSERT INTO thesis_files (thesis_id, file_type, file_path, file_name, file_size, mime_type, display_label)
VALUES (?, 'website', 'https://old.example.com', 'old.example.com', 0, 'text/html', 'Old Label')"
)->execute([$thesisId]);
$oldId = (int)$pdo->lastInsertId();
// Submit the SAME URL (no change intended)
$post = ['website_url' => 'https://old.example.com'];
$this->invokeHandleWebsiteUrl($thesisId, $post);
// The row should still exist with the same ID and (crucially) preserved label
$row = $pdo->query("SELECT * FROM thesis_files WHERE thesis_id = $thesisId AND file_type = 'website'")->fetch();
$this->assertNotFalse($row, 'Website row should still exist');
$this->assertSame($oldId, (int)$row['id'], 'Row ID should be preserved (not delete+reinsert)');
$this->assertSame('Old Label', $row['display_label'], 'Label should be preserved when no new label is given');
$this->assertSame('https://old.example.com', $row['file_path']);
}
public function testHandleWebsiteUrlPreservesLabelWhenNotProvided(): void
{
[$authorId, $thesisId] = TestDatabase::seedBasicThesis('Label Preserve', 'Author', 2024);
$pdo = TestDatabase::getPDO();
$pdo->prepare(
"INSERT INTO thesis_files (thesis_id, file_type, file_path, file_name, file_size, mime_type, display_label)
VALUES (?, 'website', 'https://example.com', 'example.com', 0, 'text/html', 'My Custom Label')"
)->execute([$thesisId]);
// Submit URL without a label
$post = ['website_url' => 'https://example.com', 'website_label' => ''];
$this->invokeHandleWebsiteUrl($thesisId, $post);
$row = $pdo->query("SELECT * FROM thesis_files WHERE thesis_id = $thesisId AND file_type = 'website'")->fetch();
$this->assertSame('My Custom Label', $row['display_label'], 'Existing label should survive when no new label is provided');
}
public function testHandleWebsiteUrlUpdatesLabelWhenProvided(): void
{
[$authorId, $thesisId] = TestDatabase::seedBasicThesis('Label Update', 'Author', 2024);
$pdo = TestDatabase::getPDO();
$pdo->prepare(
"INSERT INTO thesis_files (thesis_id, file_type, file_path, file_name, file_size, mime_type, display_label)
VALUES (?, 'website', 'https://example.com', 'example.com', 0, 'text/html', 'Old Label')"
)->execute([$thesisId]);
$post = ['website_url' => 'https://example.com', 'website_label' => 'New Label'];
$this->invokeHandleWebsiteUrl($thesisId, $post);
$row = $pdo->query("SELECT * FROM thesis_files WHERE thesis_id = $thesisId AND file_type = 'website'")->fetch();
$this->assertSame('New Label', $row['display_label']);
}
public function testHandleWebsiteUrlDeletesRowWhenUrlExplicitlyCleared(): void
{
[$authorId, $thesisId] = TestDatabase::seedBasicThesis('Clear Site', 'Author', 2024);
$pdo = TestDatabase::getPDO();
$pdo->prepare(
"INSERT INTO thesis_files (thesis_id, file_type, file_path, file_name, file_size, mime_type, display_label)
VALUES (?, 'website', 'https://example.com', 'example.com', 0, 'text/html', 'Label')"
)->execute([$thesisId]);
// Explicitly clear the URL
$post = ['website_url' => ''];
$this->invokeHandleWebsiteUrl($thesisId, $post);
$count = $pdo->query("SELECT COUNT(*) FROM thesis_files WHERE thesis_id = $thesisId AND file_type = 'website'")->fetchColumn();
$this->assertSame(0, (int)$count, 'Website row should be deleted when URL is explicitly cleared');
}
public function testHandleWebsiteUrlUpdatesUrlWhenChanged(): void
{
[$authorId, $thesisId] = TestDatabase::seedBasicThesis('Change URL', 'Author', 2024);
$pdo = TestDatabase::getPDO();
$pdo->prepare(
"INSERT INTO thesis_files (thesis_id, file_type, file_path, file_name, file_size, mime_type, display_label)
VALUES (?, 'website', 'https://old.example.com', 'old.example.com', 0, 'text/html', 'Label')"
)->execute([$thesisId]);
$oldId = (int)$pdo->lastInsertId();
$post = ['website_url' => 'https://new.example.com'];
$this->invokeHandleWebsiteUrl($thesisId, $post);
$row = $pdo->query("SELECT * FROM thesis_files WHERE thesis_id = $thesisId AND file_type = 'website'")->fetch();
$this->assertSame($oldId, (int)$row['id'], 'Row ID should be preserved on URL update');
$this->assertSame('https://new.example.com', $row['file_path']);
$this->assertSame('Label', $row['display_label'], 'Label should be preserved on URL-only change');
}
public function testHandleWebsiteUrlNoExistingRowEmptyUrlDoesNothing(): void
{
[$authorId, $thesisId] = TestDatabase::seedBasicThesis('Noop', 'Author', 2024);
$pdo = TestDatabase::getPDO();
// Should not error even with no existing row
$post = ['website_url' => ''];
$this->invokeHandleWebsiteUrl($thesisId, $post);
$count = $pdo->query("SELECT COUNT(*) FROM thesis_files WHERE thesis_id = $thesisId AND file_type = 'website'")->fetchColumn();
$this->assertSame(0, (int)$count);
// All other files should still be intact
$totalFiles = $pdo->query("SELECT COUNT(*) FROM thesis_files WHERE thesis_id = $thesisId")->fetchColumn();
$this->assertGreaterThan(0, (int)$totalFiles, 'Cover file from seeding should still exist');
}
} }