media-library search, MIME-type and virtual-folder filters, persisted

folder and alt-text editing, and safe defaults for legacy uploads
This commit is contained in:
2026-11-30 16:51:14 +01:00
parent 1ec2d9c8e1
commit e1767dcd2c
7 changed files with 654 additions and 9 deletions
@@ -26,6 +26,15 @@ class WebsiteManager implements WebsiteManagerContract
exit();
}
if ($route === 'media' && $action === 'update_metadata') {
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
exit();
}
$this->handleUpdateMediaMetadata();
exit();
}
if ($route === 'quality' && $action === 'scan' && ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
if (! function_exists('phpb_validate_csrf') || ! phpb_validate_csrf()) {
http_response_code(403);
@@ -83,6 +92,45 @@ class WebsiteManager implements WebsiteManagerContract
}
}
/**
* Handle a CSRF-protected update to upload metadata.
*/
public function handleUpdateMediaMetadata(): bool
{
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
return false;
}
if (! function_exists('phpb_validate_csrf') || ! phpb_validate_csrf()) {
http_response_code(403);
return false;
}
$allowedFields = ['_csrf_token', 'public_id', 'folder', 'alt_text'];
if (array_diff(array_keys($_POST), $allowedFields)) {
return $this->redirectMediaMetadataResult(false);
}
$publicId = $_POST['public_id'] ?? null;
$metadata = array_intersect_key($_POST, array_flip(['folder', 'alt_text']));
if (! is_string($publicId) || $publicId === '' || empty($metadata)) {
return $this->redirectMediaMetadataResult(false);
}
$success = (new UploadRepository)->updateMetadata($publicId, $metadata);
return $this->redirectMediaMetadataResult($success);
}
private function redirectMediaMetadataResult(bool $success): bool
{
phpb_redirect(phpb_url('website_manager', ['tab' => 'files']), [
'message-type' => $success ? 'success' : 'error',
'message' => $success ? 'Media metadata updated.' : 'Media metadata could not be updated.',
]);
return $success;
}
/**
* Handle requests for creating a new page.
*/
@@ -1,3 +1,33 @@
<?php
$mediaFiles = [];
$mediaFileTypes = [];
$mediaFolders = [];
foreach ($files as $file) {
$mimeType = strtolower(trim((string) ($file->mime_type ?? '')));
$mimeFamily = str_contains($mimeType, '/') ? strstr($mimeType, '/', true) : 'other';
$folder = trim((string) ($file->folder ?? ''));
$mediaFiles[] = [
'file' => $file,
'mimeType' => $mimeType,
'mimeFamily' => $mimeFamily,
'folder' => $folder,
'isImage' => str_starts_with($mimeType, 'image/'),
];
$mediaFileTypes[$mimeFamily] = match ($mimeFamily) {
'image' => 'Images',
'video' => 'Videos',
'audio' => 'Audio',
'text' => 'Text files',
'application' => 'Documents and other files',
default => ucfirst($mimeFamily) . ' files',
};
if ($folder !== '') {
$mediaFolders[$folder] = $folder;
}
}
ksort($mediaFileTypes, SORT_NATURAL | SORT_FLAG_CASE);
ksort($mediaFolders, SORT_NATURAL | SORT_FLAG_CASE);
?>
<section class="card border border-base-300 bg-base-100 shadow-sm">
<div class="card-body gap-6 p-4 sm:p-6 lg:p-8">
<div class="flex flex-col gap-5 border-b border-base-300 pb-5 sm:flex-row sm:items-end sm:justify-between">
@@ -23,26 +53,157 @@
<p class="mt-1 text-sm text-base-content/60">Your uploaded files will appear here as a visual library.</p>
</div>
<?php else : ?>
<ul class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
<?php foreach ($files as $file) : ?>
<li class="card overflow-hidden border border-base-300 bg-base-100 shadow-sm transition-shadow hover:shadow-md">
<section class="space-y-4" aria-label="Filter media library">
<div class="grid gap-3 md:grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,1fr)_auto] md:items-end">
<label class="flex flex-col gap-1 text-sm font-medium" for="media-search">
<span>Search uploads</span>
<input id="media-search" type="search" class="input w-full" placeholder="Filename or public ID" autocomplete="off">
</label>
<label class="flex flex-col gap-1 text-sm font-medium" for="media-type-filter">
<span>File type</span>
<select id="media-type-filter" class="select w-full">
<option value="">All types</option>
<?php foreach ($mediaFileTypes as $mimeFamily => $label) : ?>
<option value="<?= phpb_e($mimeFamily) ?>"><?= phpb_e($label) ?></option>
<?php endforeach; ?>
</select>
</label>
<label class="flex flex-col gap-1 text-sm font-medium" for="media-folder-filter">
<span>Folder</span>
<select id="media-folder-filter" class="select w-full">
<option value="">All folders</option>
<option value="__unsorted__">Unsorted</option>
<?php foreach ($mediaFolders as $folder) : ?>
<option value="folder:<?= phpb_e($folder) ?>"><?= phpb_e($folder) ?></option>
<?php endforeach; ?>
</select>
</label>
<button id="media-filter-reset" type="button" class="btn btn-ghost">Clear filters</button>
</div>
<p id="media-results-count" class="text-sm text-base-content/60" role="status" aria-live="polite"></p>
</section>
<datalist id="media-folder-suggestions">
<?php foreach ($mediaFolders as $folder) : ?>
<option value="<?= phpb_e($folder) ?>"></option>
<?php endforeach; ?>
</datalist>
<ul id="media-library-items" class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
<?php foreach ($mediaFiles as $mediaFile) :
$file = $mediaFile['file'];
$mimeType = $mediaFile['mimeType'];
$publicId = (string) ($file->public_id ?? '');
$originalFile = (string) ($file->original_file ?? '');
$folder = $mediaFile['folder'];
$altText = (string) ($file->alt_text ?? '');
?>
<li class="media-library-item card overflow-hidden border border-base-300 bg-base-100 shadow-sm transition-shadow hover:shadow-md"
data-media-library-item
data-file-name="<?= phpb_e($originalFile) ?>"
data-public-id="<?= phpb_e($publicId) ?>"
data-mime-family="<?= phpb_e($mediaFile['mimeFamily']) ?>"
data-folder="<?= phpb_e($folder) ?>">
<figure class="relative aspect-video bg-base-200">
<img src="<?= phpb_e($file->getUrl()) ?>" alt="<?= phpb_e($file->public_id) ?>" class="h-full w-full object-cover">
<button type="button" onclick="deleteFile('<?= phpb_e($file->public_id) ?>')" class="btn btn-error btn-square btn-sm absolute right-3 top-3 shadow-sm" aria-label="<?= phpb_e(phpb_trans('website-manager.remove')) ?> <?= phpb_e($file->public_id) ?>" title="<?= phpb_e(phpb_trans('website-manager.remove')) ?>">
<?php if ($mediaFile['isImage']) : ?>
<img src="<?= phpb_e($file->getUrl()) ?>" alt="<?= phpb_e($altText) ?>" class="h-full w-full object-cover">
<?php else : ?>
<div class="flex h-full w-full flex-col items-center justify-center gap-2 p-4 text-center text-base-content/70">
<i class="text-4xl ph-duotone ph-file" aria-hidden="true"></i>
<span class="text-xs font-medium"><?= phpb_e($mimeType !== '' ? $mimeType : 'Unknown file type') ?></span>
</div>
<?php endif; ?>
<button type="button" onclick="deleteFile('<?= phpb_e($publicId) ?>')" class="btn btn-error btn-square btn-sm absolute right-3 top-3 shadow-sm" aria-label="<?= phpb_e(phpb_trans('website-manager.remove')) ?> <?= phpb_e($publicId) ?>" title="<?= phpb_e(phpb_trans('website-manager.remove')) ?>">
<i class="ph-duotone ph-trash" aria-hidden="true"></i>
</button>
</figure>
<div class="card-body gap-1 p-3">
<p class="truncate text-sm font-medium" title="<?= phpb_e($file->public_id) ?>"><?= phpb_e($file->public_id) ?></p>
<div class="card-body gap-3 p-3">
<div class="min-w-0 space-y-1">
<p class="truncate text-sm font-medium" title="<?= phpb_e($originalFile) ?>"><?= phpb_e($originalFile !== '' ? $originalFile : $publicId) ?></p>
<p class="truncate text-xs text-base-content/60" title="<?= phpb_e($publicId) ?>"><?= phpb_e($publicId) ?></p>
</div>
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'media', 'action' => 'update_metadata']) ?>" class="flex flex-col gap-2 sm:flex-row sm:items-end" aria-label="Assign folder for <?= phpb_e($originalFile !== '' ? $originalFile : $publicId) ?>">
<?php phpb_csrf_field(); ?>
<input type="hidden" name="public_id" value="<?= phpb_e($publicId) ?>">
<label class="flex min-w-0 flex-1 flex-col gap-1 text-xs font-medium">
<span>Folder</span>
<input type="text" name="folder" class="input input-sm w-full" list="media-folder-suggestions" maxlength="255" value="<?= phpb_e($folder) ?>" placeholder="Unsorted">
</label>
<button type="submit" class="btn btn-sm">Save folder</button>
</form>
<form method="post" action="<?= phpb_url('website_manager', ['route' => 'media', 'action' => 'update_metadata']) ?>" class="flex flex-col gap-2" aria-label="Edit alt text for <?= phpb_e($originalFile !== '' ? $originalFile : $publicId) ?>">
<?php phpb_csrf_field(); ?>
<input type="hidden" name="public_id" value="<?= phpb_e($publicId) ?>">
<label class="flex flex-col gap-1 text-xs font-medium">
<span>Alt text</span>
<input type="text" name="alt_text" class="input input-sm w-full" maxlength="1000" value="<?= phpb_e($altText) ?>" placeholder="Describe the image">
</label>
<button type="submit" class="btn btn-sm">Save alt text</button>
</form>
</div>
</li>
<?php endforeach; ?>
</ul>
<div id="media-no-results" class="hidden rounded-box border border-dashed border-base-300 bg-base-200/50 px-5 py-10 text-center" role="status">
<h3 class="font-semibold text-base-content">No matching files</h3>
<p class="mt-1 text-sm text-base-content/60">Try changing or clearing your filters.</p>
</div>
<?php endif; ?>
</div>
</section>
<script>
document.addEventListener('DOMContentLoaded', function() {
const items = Array.from(document.querySelectorAll('[data-media-library-item]'));
const search = document.getElementById('media-search');
const typeFilter = document.getElementById('media-type-filter');
const folderFilter = document.getElementById('media-folder-filter');
const resultCount = document.getElementById('media-results-count');
const noResults = document.getElementById('media-no-results');
const itemList = document.getElementById('media-library-items');
if (!search || !typeFilter || !folderFilter || !resultCount || !noResults || !itemList) {
return;
}
function filterMediaLibrary() {
const query = search.value.trim().toLocaleLowerCase();
const selectedType = typeFilter.value;
const selectedFolder = folderFilter.value;
let visibleCount = 0;
items.forEach(function(item) {
const matchesSearch = item.dataset.fileName.toLocaleLowerCase().includes(query)
|| item.dataset.publicId.toLocaleLowerCase().includes(query);
const matchesType = selectedType === '' || item.dataset.mimeFamily === selectedType;
const matchesFolder = selectedFolder === ''
|| (selectedFolder === '__unsorted__' && item.dataset.folder === '')
|| (selectedFolder.startsWith('folder:') && item.dataset.folder === selectedFolder.slice(7));
const matches = matchesSearch && matchesType && matchesFolder;
item.hidden = !matches;
if (matches) {
visibleCount++;
}
});
resultCount.textContent = `Showing ${visibleCount} of ${items.length} files`;
noResults.classList.toggle('hidden', visibleCount !== 0);
itemList.classList.toggle('hidden', visibleCount === 0);
}
search.addEventListener('input', filterMediaLibrary);
typeFilter.addEventListener('change', filterMediaLibrary);
folderFilter.addEventListener('change', filterMediaLibrary);
document.getElementById('media-filter-reset').addEventListener('click', function() {
search.value = '';
typeFilter.value = '';
folderFilter.value = '';
filterMediaLibrary();
});
filterMediaLibrary();
});
async function uploadFile() {
let formData = new FormData();
const fileupload = document.getElementById('fileupload');