„Dokumente“ heißt jetzt „Downloads“
All checks were successful
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m38s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m31s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m39s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 3m54s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 3m50s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 3m55s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 3m18s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 3m19s
CI / Build-Artefakte aktuell (pull_request) Successful in 55s
All checks were successful
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m38s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m31s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m39s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 3m54s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 3m50s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 3m55s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 3m18s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 3m19s
CI / Build-Artefakte aktuell (pull_request) Successful in 55s
Der Name „Dokumente“ bleibt dem kommenden QM-Modul (QM-Dokumente und -Formulare) vorbehalten. - Plugin plugins-core/downloads (Inhaus\Plugins\Downloads), Adresse /downloads, Rechte downloads.*, Objekttyp download_folder, Block downloads.folder, Kachel downloads.favorites - Migration für bestehende Installationen: Tabellen und Spalten, Rechte, Sichtbarkeiten, Menü, Startseiten-Anordnung, Blöcke in Seiten und Fassungen, Plugin-Zustand; mit Test - Alte Links unter /dokumente leiten dauerhaft weiter Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
c71131d054
commit
f78cc96be7
120 changed files with 1091 additions and 866 deletions
|
|
@ -0,0 +1,351 @@
|
|||
<?php
|
||||
|
||||
namespace Inhaus\Plugins\Downloads\Http\Controllers;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\Grant;
|
||||
use App\Support\Audit;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
use Inhaus\Plugins\Downloads\DownloadPresenter;
|
||||
use Inhaus\Plugins\Downloads\FolderTree;
|
||||
use Inhaus\Plugins\Downloads\Models\Download;
|
||||
use Inhaus\Plugins\Downloads\Models\DownloadFolder;
|
||||
use Inhaus\Plugins\Downloads\Models\DownloadVersion;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
class DownloadController extends Controller
|
||||
{
|
||||
/** Nie als Datei annehmen: ausführbarer Code, Webseiten, Skripte. */
|
||||
private const BLOCKED = ['php', 'phtml', 'phar', 'php3', 'php4', 'php5', 'php7', 'php8', 'pht', 'shtml', 'htaccess', 'exe', 'bat', 'cmd', 'com', 'sh', 'js', 'mjs', 'html', 'htm', 'svg', 'xhtml', 'jsp', 'asp', 'aspx', 'cgi', 'pl', 'py', 'msi', 'ps1', 'vbs', 'scr'];
|
||||
|
||||
public const MAX_KB = 100 * 1024;
|
||||
|
||||
public function __construct(private readonly FolderTree $tree) {}
|
||||
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
return $this->render($request, null);
|
||||
}
|
||||
|
||||
public function folder(Request $request, DownloadFolder $folder): Response
|
||||
{
|
||||
abort_unless($this->tree->isVisible($folder->id, $request->user()) || $request->user()->can('update', $folder), 404);
|
||||
|
||||
return $this->render($request, $folder);
|
||||
}
|
||||
|
||||
public function upload(Request $request, DownloadFolder $folder): RedirectResponse
|
||||
{
|
||||
Gate::authorize('update', $folder);
|
||||
$request->validate([
|
||||
'files' => ['required', 'array', 'max:20'],
|
||||
'files.*' => ['file', 'max:'.self::MAX_KB],
|
||||
], [], ['files.*' => 'Datei']);
|
||||
|
||||
$count = 0;
|
||||
|
||||
foreach ($request->file('files') as $index => $file) {
|
||||
$this->assertAllowed($file, "files.{$index}");
|
||||
}
|
||||
|
||||
foreach ($request->file('files') as $file) {
|
||||
DB::transaction(function () use ($folder, $file, $request) {
|
||||
$download = $folder->downloads()->create([
|
||||
'title' => Str::limit(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME) ?: 'Datei', 250, ''),
|
||||
'created_by' => $request->user()->id,
|
||||
'updated_by' => $request->user()->id,
|
||||
]);
|
||||
$this->storeVersion($download, $file, $request, null);
|
||||
});
|
||||
$count++;
|
||||
}
|
||||
|
||||
Audit::log('downloads.uploaded', ['folder' => $folder->id, 'count' => $count]);
|
||||
|
||||
return back()->with('status', $count === 1 ? 'Datei hochgeladen.' : "{$count} Dateien hochgeladen.");
|
||||
}
|
||||
|
||||
public function newVersion(Request $request, Download $download): RedirectResponse
|
||||
{
|
||||
Gate::authorize('update', $download->folder);
|
||||
$request->validate(['file' => ['required', 'file', 'max:'.self::MAX_KB], 'note' => ['nullable', 'string', 'max:500']], [], ['file' => 'Datei', 'note' => 'Hinweis']);
|
||||
$this->assertAllowed($request->file('file'), 'file');
|
||||
|
||||
DB::transaction(fn () => $this->storeVersion($download, $request->file('file'), $request, $request->input('note')));
|
||||
Audit::log('downloads.version_added', ['download' => $download->id, 'title' => $download->title]);
|
||||
|
||||
return back()->with('status', 'Neue Fassung hochgeladen.');
|
||||
}
|
||||
|
||||
public function update(Request $request, Download $download): RedirectResponse
|
||||
{
|
||||
Gate::authorize('update', $download->folder);
|
||||
$data = $request->validate([
|
||||
'title' => ['required', 'string', 'max:250'],
|
||||
'description' => ['nullable', 'string', 'max:2000'],
|
||||
'folder_id' => ['required', 'integer', Rule::exists('download_folders', 'id')],
|
||||
], [], ['title' => 'Titel', 'folder_id' => 'Ordner']);
|
||||
|
||||
// Verschieben: im Zielordner muss man ebenfalls pflegen dürfen.
|
||||
if ((int) $data['folder_id'] !== $download->folder_id) {
|
||||
Gate::authorize('update', DownloadFolder::query()->findOrFail($data['folder_id']));
|
||||
}
|
||||
|
||||
$download->update([...$data, 'updated_by' => $request->user()->id]);
|
||||
|
||||
return back()->with('status', 'Gespeichert.');
|
||||
}
|
||||
|
||||
public function destroy(Request $request, Download $download): RedirectResponse
|
||||
{
|
||||
Gate::authorize('update', $download->folder);
|
||||
$download->delete();
|
||||
Audit::log('downloads.deleted', ['download' => $download->id, 'title' => $download->title]);
|
||||
|
||||
return back()->with('status', 'Datei gelöscht.');
|
||||
}
|
||||
|
||||
public function versions(Request $request, Download $download): JsonResponse
|
||||
{
|
||||
abort_unless($this->tree->isVisible($download->folder_id, $request->user()) || $request->user()->can('update', $download->folder), 404);
|
||||
|
||||
return response()->json(['versions' => $download->versions()->with('uploader:id,name')->get()->map(fn (DownloadVersion $v) => [
|
||||
'version' => $v->version,
|
||||
'name' => $v->name,
|
||||
'size' => (int) $v->size,
|
||||
'note' => $v->note,
|
||||
'uploader' => $v->uploader?->name,
|
||||
'created_at' => $v->created_at?->toIso8601String(),
|
||||
'current' => $v->id === $download->current_version_id,
|
||||
'download_url' => $download->downloadUrl($v),
|
||||
])]);
|
||||
}
|
||||
|
||||
public function download(Request $request, Download $download, int $version): StreamedResponse
|
||||
{
|
||||
abort_unless($this->tree->isVisible($download->folder_id, $request->user()) || $request->user()->can('update', $download->folder), 404);
|
||||
|
||||
$file = $download->versions()->where('version', $version)->firstOrFail();
|
||||
|
||||
// Vorschaubild (Kachelansicht): nur ungefährliche Typen, im Browser anzeigen, nicht mitzählen.
|
||||
if ($request->boolean('vorschau')) {
|
||||
abort_unless(in_array($file->mime, DownloadPresenter::PREVIEW_MIMES, true), 404);
|
||||
|
||||
return Storage::disk(DownloadVersion::DISK)->response($file->path, $file->name, [
|
||||
'Content-Type' => $file->mime,
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
'Content-Security-Policy' => "default-src 'none'; sandbox",
|
||||
'Cache-Control' => 'private, max-age=3600',
|
||||
]);
|
||||
}
|
||||
|
||||
// Ohne updated_at zu ändern – ein Download ist keine Bearbeitung.
|
||||
DB::table('downloads')->where('id', $download->id)->increment('download_count');
|
||||
|
||||
return Storage::disk(DownloadVersion::DISK)->download($file->path, $file->name, [
|
||||
'Content-Type' => $file->mime ?: 'application/octet-stream',
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
'Cache-Control' => 'private, max-age=300',
|
||||
]);
|
||||
}
|
||||
|
||||
public function favorite(Request $request, Download $download): RedirectResponse
|
||||
{
|
||||
abort_unless($this->tree->isVisible($download->folder_id, $request->user()), 404);
|
||||
|
||||
DB::table('download_favorites')->insertOrIgnore(['user_id' => $request->user()->id, 'download_id' => $download->id, 'created_at' => now()]);
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
public function unfavorite(Request $request, Download $download): RedirectResponse
|
||||
{
|
||||
DB::table('download_favorites')->where('user_id', $request->user()->id)->where('download_id', $download->id)->delete();
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
public function storeFolder(Request $request): RedirectResponse
|
||||
{
|
||||
$data = $request->validate([
|
||||
'name' => ['required', 'string', 'max:120'],
|
||||
'parent_id' => ['nullable', 'integer', Rule::exists('download_folders', 'id')],
|
||||
], [], ['name' => 'Name']);
|
||||
|
||||
$parent = isset($data['parent_id']) ? DownloadFolder::query()->findOrFail($data['parent_id']) : null;
|
||||
Gate::authorize('create', [DownloadFolder::class, $parent]);
|
||||
|
||||
$folder = DownloadFolder::query()->create([
|
||||
'name' => trim($data['name']),
|
||||
'parent_id' => $parent?->id,
|
||||
'sort' => (int) DownloadFolder::query()->where('parent_id', $parent?->id)->max('sort') + 1,
|
||||
'created_by' => $request->user()->id,
|
||||
]);
|
||||
|
||||
return to_route('downloads.folder', $folder)->with('status', 'Ordner angelegt.');
|
||||
}
|
||||
|
||||
public function updateFolder(Request $request, DownloadFolder $folder): RedirectResponse
|
||||
{
|
||||
Gate::authorize('update', $folder);
|
||||
$folder->update($request->validate(['name' => ['required', 'string', 'max:120'], 'description' => ['nullable', 'string', 'max:500']], [], ['name' => 'Name']));
|
||||
|
||||
return back()->with('status', 'Ordner gespeichert.');
|
||||
}
|
||||
|
||||
public function destroyFolder(Request $request, DownloadFolder $folder): RedirectResponse
|
||||
{
|
||||
Gate::authorize('delete', $folder);
|
||||
|
||||
if ($folder->children()->exists() || $folder->downloads()->exists()) {
|
||||
throw ValidationException::withMessages(['folder' => 'Der Ordner ist nicht leer. Bitte zuerst Dateien und Unterordner entfernen oder verschieben.']);
|
||||
}
|
||||
|
||||
$parent = $folder->parent_id;
|
||||
$folder->delete();
|
||||
|
||||
return ($parent ? to_route('downloads.folder', $parent) : to_route('downloads.index'))->with('status', 'Ordner gelöscht.');
|
||||
}
|
||||
|
||||
private function render(Request $request, ?DownloadFolder $folder): Response
|
||||
{
|
||||
$user = $request->user();
|
||||
$search = trim((string) $request->query('q', ''));
|
||||
|
||||
if ($search !== '') {
|
||||
$like = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $search).'%';
|
||||
$downloads = Download::query()
|
||||
->whereIn('folder_id', $this->tree->visibleIds($user) ?: [0])
|
||||
->where(fn ($q) => $q->where('title', 'like', $like)->orWhere('description', 'like', $like)
|
||||
->orWhereHas('versions', fn ($v) => $v->where('name', 'like', $like)))
|
||||
->with('currentVersion.uploader')->orderBy('title')->limit(100)->get();
|
||||
} else {
|
||||
$downloads = $folder
|
||||
? $folder->downloads()->with('currentVersion.uploader')->orderBy('title')->get()
|
||||
: collect();
|
||||
}
|
||||
|
||||
// Startseite der Ablage: zuletzt geänderte Dateien aus allen sichtbaren Ordnern.
|
||||
$recent = ! $folder && $search === ''
|
||||
? Download::query()->whereIn('folder_id', $this->tree->visibleIds($user) ?: [0])
|
||||
->with('currentVersion.uploader')->latest('updated_at')->limit(8)->get()
|
||||
: collect();
|
||||
$favoriteIds = DB::table('download_favorites')->where('user_id', $user->id)->pluck('download_id')->flip();
|
||||
$visible = $this->tree->visibleIds($user) ?: [0];
|
||||
$favorites = ! $folder && $search === ''
|
||||
? Download::query()->whereIn('id', $favoriteIds->keys()->all() ?: [0])->whereIn('folder_id', $visible)
|
||||
->with('currentVersion.uploader')->orderBy('title')->limit(24)->get()
|
||||
: collect();
|
||||
$popular = ! $folder && $search === ''
|
||||
? Download::query()->whereIn('folder_id', $visible)->where('download_count', '>', 0)
|
||||
->with('currentVersion.uploader')->orderByDesc('download_count')->orderBy('title')->limit(6)->get()
|
||||
: collect();
|
||||
$folderName = fn (Download $d) => ($folder && $search === '') ? null : ($this->tree->get($d->folder_id)['name'] ?? null);
|
||||
|
||||
$childIds = array_values(array_filter($this->tree->childIds($folder?->id), fn ($id) => $this->tree->isVisible($id, $user)));
|
||||
$counts = Download::query()->whereIn('folder_id', $childIds ?: [0])->selectRaw('folder_id, count(*) as c')->groupBy('folder_id')->pluck('c', 'folder_id');
|
||||
$descriptions = DownloadFolder::query()->whereIn('id', $childIds ?: [0])->pluck('description', 'id');
|
||||
$visibleChildren = fn (int $id) => array_values(array_filter($this->tree->childIds($id), fn ($c) => $this->tree->isVisible($c, $user)));
|
||||
$children = collect($childIds)->map(fn ($id) => [
|
||||
'id' => $id,
|
||||
'name' => $this->tree->get($id)['name'],
|
||||
'description' => $descriptions[$id] ?? null,
|
||||
'downloads' => (int) ($counts[$id] ?? 0),
|
||||
'folders' => count($visibleChildren($id)),
|
||||
'subfolders' => array_map(fn ($c) => ['id' => $c, 'name' => $this->tree->get($c)['name']], array_slice($visibleChildren($id), 0, 4)),
|
||||
'count' => (int) ($counts[$id] ?? 0) + count($this->tree->childIds($id)),
|
||||
]);
|
||||
|
||||
return Inertia::render('downloads::Index', [
|
||||
'tree' => $this->tree->visibleTree(null, $user),
|
||||
'folder' => $folder ? [
|
||||
'id' => $folder->id,
|
||||
'name' => $folder->name,
|
||||
'description' => $folder->description,
|
||||
'parent_id' => $folder->parent_id,
|
||||
'can_edit' => $user->can('update', $folder),
|
||||
'can_delete' => $user->can('delete', $folder),
|
||||
'editors' => $this->editorRoles($folder),
|
||||
] : null,
|
||||
'breadcrumbs' => $folder ? array_map(fn ($f) => ['id' => $f['id'], 'name' => $f['name']], $this->tree->ancestors($folder->id)) : [],
|
||||
'children' => $children,
|
||||
'downloads' => $downloads->map($row = fn (Download $d) => DownloadPresenter::row($d, $folderName($d), $favoriteIds->has($d->id))),
|
||||
'recent' => $recent->map($row),
|
||||
'favorites' => $favorites->map($row),
|
||||
'popular' => $popular->map($row),
|
||||
'search' => $search,
|
||||
'canCreateRoot' => $user->can('downloads.manage'),
|
||||
// Zielordner zum Verschieben: nur solche, in denen die Person pflegen darf.
|
||||
'folderOptions' => collect($this->tree->options())->filter(fn ($name, $id) => $user->can('downloads.edit', ['download_folder', $id]))
|
||||
->map(fn ($name, $id) => ['value' => $id, 'label' => $name])->values(),
|
||||
'maxUploadMb' => (int) floor(min(self::MAX_KB / 1024, self::phpUploadLimitMb())),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rollen, die diesen Ordner pflegen dürfen – direkt oder über einen übergeordneten
|
||||
* Ordner mit „inkl. Unterordnern“.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private function editorRoles(DownloadFolder $folder): array
|
||||
{
|
||||
$ancestors = array_column($this->tree->ancestors($folder->id), 'id');
|
||||
|
||||
return Grant::query()
|
||||
->where('ability', 'downloads.edit')->where('resource_type', 'download_folder')
|
||||
->where(fn ($q) => $q->where('resource_id', $folder->id)
|
||||
->orWhere(fn ($q) => $q->whereIn('resource_id', array_diff($ancestors, [$folder->id]) ?: [0])->where('include_children', true)))
|
||||
->with('role:id,name')->get()
|
||||
->pluck('role.name')->filter()->unique()->sort()->values()->all();
|
||||
}
|
||||
|
||||
private function storeVersion(Download $download, UploadedFile $file, Request $request, ?string $note): DownloadVersion
|
||||
{
|
||||
$name = Str::limit(preg_replace('/[^\pL\pN ._()\-]+/u', '_', $file->getClientOriginalName()) ?: 'datei', 200, '');
|
||||
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
|
||||
|
||||
$version = $download->versions()->create([
|
||||
'version' => (int) $download->versions()->max('version') + 1,
|
||||
'name' => $name,
|
||||
'path' => $file->storeAs('downloads/'.$download->folder_id, Str::random(40).($extension ? '.'.$extension : ''), DownloadVersion::DISK),
|
||||
'mime' => $file->getMimeType(),
|
||||
'size' => $file->getSize(),
|
||||
'note' => $note,
|
||||
'uploaded_by' => $request->user()->id,
|
||||
'created_at' => now(),
|
||||
]);
|
||||
|
||||
$download->forceFill(['current_version_id' => $version->id, 'updated_by' => $request->user()->id])->save();
|
||||
|
||||
return $version;
|
||||
}
|
||||
|
||||
private function assertAllowed(UploadedFile $file, string $field): void
|
||||
{
|
||||
$extensions = [strtolower(pathinfo($file->getClientOriginalName(), PATHINFO_EXTENSION)), strtolower((string) $file->getClientOriginalExtension())];
|
||||
|
||||
if (array_intersect($extensions, self::BLOCKED) !== []) {
|
||||
throw ValidationException::withMessages([$field => '„'.$file->getClientOriginalName().'“: Dieser Dateityp ist aus Sicherheitsgründen nicht erlaubt.']);
|
||||
}
|
||||
}
|
||||
|
||||
private static function phpUploadLimitMb(): float
|
||||
{
|
||||
$bytes = fn (string $v) => (int) $v * (['g' => 1024 ** 3, 'm' => 1024 ** 2, 'k' => 1024][strtolower(substr(trim($v), -1))] ?? 1);
|
||||
$limits = array_filter([$bytes((string) ini_get('upload_max_filesize')), $bytes((string) ini_get('post_max_size'))]);
|
||||
|
||||
return $limits === [] ? self::MAX_KB / 1024 : min($limits) / 1024 / 1024;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue