„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

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:
Friederich Loheide 2026-09-26 15:03:32 +00:00
parent c71131d054
commit f78cc96be7
120 changed files with 1091 additions and 866 deletions

View file

@ -0,0 +1,42 @@
<?php
namespace Inhaus\Plugins\Downloads;
use Inhaus\Plugins\Downloads\Models\Download;
final class DownloadPresenter
{
/**
* @return array<string, mixed>
*/
/** Dateitypen, die für Vorschaubilder im Browser ausgeliefert werden (kein SVG/HTML). */
public const PREVIEW_MIMES = ['application/pdf', 'image/jpeg', 'image/png', 'image/gif', 'image/webp'];
/** Größere PDFs lädt die Kachelansicht nicht für ein Vorschaubild. */
public const PREVIEW_MAX_BYTES = 8 * 1024 * 1024;
public static function row(Download $download, ?string $folderName = null, bool $favorite = false): array
{
$version = $download->currentVersion;
$previewable = $version && in_array($version->mime, self::PREVIEW_MIMES, true) && $version->size <= self::PREVIEW_MAX_BYTES;
return [
'id' => $download->id,
'title' => $download->title,
'description' => $download->description,
'folder_id' => $download->folder_id,
'folder_name' => $folderName,
'version' => $version?->version,
'name' => $version?->name,
'extension' => $version?->extension(),
'size' => (int) ($version?->size ?? 0),
'updated_by' => $version?->relationLoaded('uploader') ? $version->uploader?->name : null,
'updated_at' => ($version?->created_at ?? $download->updated_at)?->toIso8601String(),
'download_url' => $version ? $download->downloadUrl($version) : null,
'preview_url' => $previewable ? $download->downloadUrl($version).'?vorschau=1' : null,
'preview_kind' => $previewable ? ($version->mime === 'application/pdf' ? 'pdf' : 'image') : null,
'favorite' => $favorite,
'download_count' => (int) $download->download_count,
];
}
}

View file

@ -0,0 +1,78 @@
<?php
namespace Inhaus\Plugins\Downloads;
use App\Dashboard\Widgets;
use App\Models\User;
use App\Pagebuilder\Blocks;
use App\Pagebuilder\BlockType;
use App\Pagebuilder\Field;
use App\Plugins\Plugin;
use App\Support\Abilities;
use App\Support\Navigation;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Inhaus\Plugins\Downloads\Models\Download;
use Inhaus\Plugins\Downloads\Models\DownloadFolder;
use Inhaus\Plugins\Downloads\Policies\DownloadFolderPolicy;
class DownloadsPlugin extends Plugin
{
public function register(): void
{
$this->app->singleton(FolderTree::class);
$this->app->make(Navigation::class)->add('downloads', 'Downloads', '/downloads', active: 'downloads.*', sort: 50);
$abilities = $this->app->make(Abilities::class);
$abilities->define('downloads.manage', 'Downloads: gesamten Bereich verwalten', 'Downloads');
$abilities->define('downloads.edit', 'Downloads pflegen', 'Downloads', resource: 'download_folder');
$abilities->resourceType(
'download_folder',
'Download-Ordner',
fn () => $this->app->make(FolderTree::class)->options(),
fn (array $ids) => $this->app->make(FolderTree::class)->descendantIds($ids),
);
Gate::policy(DownloadFolder::class, DownloadFolderPolicy::class);
// Startseite: gemerkte Dateien – ohne Favoriten die meistgenutzten.
$this->app->make(Widgets::class)->add('downloads.favorites', 'downloads::MyDownloads', 'aside', sort: 25, props: function (User $user) {
$visible = $this->app->make(FolderTree::class)->visibleIds($user) ?: [0];
$favorites = Download::query()->whereIn('folder_id', $visible)
->whereIn('id', DB::table('download_favorites')->where('user_id', $user->id)->select('download_id'))
->with('currentVersion')->orderBy('title')->limit(6)->get();
$popular = $favorites->isEmpty()
? Download::query()->whereIn('folder_id', $visible)->where('download_count', '>', 0)->with('currentVersion')->orderByDesc('download_count')->limit(5)->get()
: collect();
return [
'favorites' => $favorites->map(fn (Download $d) => DownloadPresenter::row($d, null, true))->all(),
'popular' => $popular->map(fn (Download $d) => DownloadPresenter::row($d))->all(),
];
}, label: 'Meine Downloads');
$this->app->make(Blocks::class)->add(BlockType::make('downloads.folder', 'Downloads', 'file-down', 'dynamic', 'downloads::FolderBlock')
->description('Die Dateien eines Download-Ordners – immer in der aktuellen Fassung.')
->fields([
Field::text('title', 'Überschrift', 150),
Field::select('folder', 'Ordner', fn () => collect($this->app->make(FolderTree::class)->options())->mapWithKeys(fn ($name, $id) => [(string) $id => $name])->all()),
Field::toggle('show_description', 'Beschreibungen anzeigen', true),
])
->resolveUsing(function (array $data, ?User $user) {
$tree = $this->app->make(FolderTree::class);
$folderId = (int) $data['folder'];
if (! $folderId || ! $tree->isVisible($folderId, $user)) {
return null;
}
$downloads = Download::query()->where('folder_id', $folderId)->with('currentVersion')->orderBy('title')->limit(100)->get();
return [
'folder_url' => route('downloads.folder', $folderId),
'downloads' => $downloads->map(fn (Download $d) => DownloadPresenter::row($d))->all(),
];
}));
}
}

View file

@ -0,0 +1,88 @@
<?php
namespace Inhaus\Plugins\Downloads\Filament\Resources\DownloadFolders;
use App\Filament\Components\AudienceSection;
use App\Filament\Components\RoleGrantSelect;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Inhaus\Plugins\Downloads\Filament\Resources\DownloadFolders\Pages\ManageDownloadFolders;
use Inhaus\Plugins\Downloads\FolderTree;
use Inhaus\Plugins\Downloads\Models\DownloadFolder;
use UnitEnum;
/**
* Ordnerstruktur des Download-Bereichs: Rechte je Ordner und Sichtbarkeit.
* Hochladen und Pflegen der Dateien geschieht im Portal unter „Downloads“.
*/
class DownloadFolderResource extends Resource
{
protected static ?string $model = DownloadFolder::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedFolder;
protected static string|UnitEnum|null $navigationGroup = 'Inhalte';
protected static ?int $navigationSort = 6;
protected static ?string $modelLabel = 'Download-Ordner';
protected static ?string $pluralModelLabel = 'Download-Ordner';
protected static ?string $slug = 'download-ordner';
public static function canAccess(): bool
{
return auth()->user()?->can('downloads.manage') ?? false;
}
public static function form(Schema $schema): Schema
{
return $schema->columns(2)->components([
TextInput::make('name')->label('Name')->required()->maxLength(120),
Select::make('parent_id')->label('Übergeordneter Ordner')->placeholder('– oberste Ebene –')->searchable()
->options(fn (?DownloadFolder $record) => collect(app(FolderTree::class)->options())
->except($record ? [$record->id, ...app(FolderTree::class)->descendantIds([$record->id])] : [])->all()),
TextInput::make('description')->label('Beschreibung')->maxLength(500)->columnSpanFull(),
TextInput::make('sort')->label('Reihenfolge')->numeric()->default(0),
Section::make('Pflege')
->description('Rollen, die in diesem Ordner und allen Unterordnern Dateien hochladen, ändern und löschen dürfen.')
->columnSpanFull()
->schema([RoleGrantSelect::make('editors', 'Dürfen Downloads pflegen', 'downloads.edit', 'download_folder', includeChildren: true)]),
AudienceSection::make('download_folder', 'Wer den Ordner sieht. Leer lassen = alle. Gilt auch für alle Unterordner.')->columnSpanFull(),
]);
}
public static function table(Table $table): Table
{
return $table
->modifyQueryUsing(fn ($query) => $query->withCount('downloads'))
->defaultSort('name')
->columns([
TextColumn::make('name')->label('Name')->weight('medium')->searchable()
->formatStateUsing(fn (string $state, DownloadFolder $record) => str_repeat('— ', count(app(FolderTree::class)->ancestors($record->id))).$state),
TextColumn::make('downloads_count')->label('Dateien'),
])
->recordActions([
Action::make('open')->label('Öffnen')->icon(Heroicon::OutlinedArrowTopRightOnSquare)->iconButton()
->url(fn (DownloadFolder $record) => route('downloads.folder', $record)),
EditAction::make()->after(fn () => FolderTree::flush(true)),
DeleteAction::make()->visible(fn (DownloadFolder $record) => $record->downloads_count === 0 && ! $record->children()->exists()),
]);
}
public static function getPages(): array
{
return ['index' => ManageDownloadFolders::route('/')];
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Inhaus\Plugins\Downloads\Filament\Resources\DownloadFolders\Pages;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ManageRecords;
use Inhaus\Plugins\Downloads\Filament\Resources\DownloadFolders\DownloadFolderResource;
use Inhaus\Plugins\Downloads\FolderTree;
class ManageDownloadFolders extends ManageRecords
{
protected static string $resource = DownloadFolderResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make()->label('Ordner anlegen')
->mutateDataUsing(fn (array $data) => [...$data, 'created_by' => auth()->id()])
->after(fn () => FolderTree::flush(true)),
];
}
}

View file

@ -0,0 +1,177 @@
<?php
namespace Inhaus\Plugins\Downloads;
use App\Models\User;
use App\Support\Permissions\Audiences;
use App\Support\Permissions\Permissions;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
/**
* Ordnerbaum als gecachte Struktur (nur Arrays). Sichtbar ist ein Ordner, wenn
* die Person seine Zielgruppe und die aller übergeordneten Ordner erfüllt.
*/
class FolderTree
{
private const CACHE_KEY = 'downloads.tree';
/** @var array{folders: array<int, array<string, mixed>>, children: array<int, list<int>>}|null */
private ?array $data = null;
/** @var array<int, array<int, bool>> */
private array $visible = [];
public static function flush(bool $structureChanged = false): void
{
Cache::forget(self::CACHE_KEY);
app(self::class)->data = null;
app(self::class)->visible = [];
if ($structureChanged) {
Permissions::flush();
}
}
/**
* @return array<string, mixed>|null
*/
public function get(int $id): ?array
{
return $this->data()['folders'][$id] ?? null;
}
/**
* @return list<int>
*/
public function childIds(?int $id): array
{
return $this->data()['children'][$id ?? 0] ?? [];
}
/**
* @param list<int> $ids
* @return list<int>
*/
public function descendantIds(array $ids): array
{
$result = [];
$queue = $ids;
while ($queue !== []) {
foreach ($this->childIds(array_shift($queue)) as $child) {
if (! in_array($child, $result, true)) {
$result[] = $child;
$queue[] = $child;
}
}
}
return $result;
}
/**
* @return list<array<string, mixed>>
*/
public function ancestors(int $id): array
{
$result = [];
$parent = $this->get($id)['parent_id'] ?? null;
while ($parent !== null && ($folder = $this->get($parent)) && count($result) < 50) {
array_unshift($result, $folder);
$parent = $folder['parent_id'];
}
return $result;
}
public function isVisible(int $id, ?User $user): bool
{
if ($user?->can('downloads.manage')) {
return $this->get($id) !== null;
}
$key = $user?->id ?? 0;
if (isset($this->visible[$key][$id])) {
return $this->visible[$key][$id];
}
$folder = $this->get($id);
$visible = $folder !== null
&& Audiences::matches($folder['audience'], $user)
&& ($folder['parent_id'] === null || $this->isVisible($folder['parent_id'], $user));
return $this->visible[$key][$id] = $visible;
}
/**
* IDs aller sichtbaren Ordner – für die Suche.
*
* @return list<int>
*/
public function visibleIds(?User $user): array
{
return array_values(array_filter(array_keys($this->data()['folders']), fn (int $id) => $this->isVisible($id, $user)));
}
/**
* @return list<array{id: int, name: string, children: list<mixed>}>
*/
public function visibleTree(?int $rootId, ?User $user, int $maxDepth = 8): array
{
if ($maxDepth <= 0) {
return [];
}
$result = [];
foreach ($this->childIds($rootId) as $id) {
if ($this->isVisible($id, $user)) {
$result[] = ['id' => $id, 'name' => $this->get($id)['name'], 'children' => $this->visibleTree($id, $user, $maxDepth - 1)];
}
}
return $result;
}
/**
* @return array<int, string>
*/
public function options(?int $rootId = null, int $depth = 0): array
{
$options = [];
foreach ($this->childIds($rootId) as $id) {
$options[$id] = str_repeat('— ', $depth).$this->get($id)['name'];
$options += $this->options($id, $depth + 1);
}
return $options;
}
/**
* @return array{folders: array<int, array<string, mixed>>, children: array<int, list<int>>}
*/
private function data(): array
{
return $this->data ??= Cache::rememberForever(self::CACHE_KEY, function () {
$audiences = Audiences::allOfType('download_folder');
$folders = [];
$children = [];
foreach (DB::table('download_folders')->orderBy('sort')->orderBy('name')->get(['id', 'parent_id', 'name']) as $row) {
$folders[$row->id] = [
'id' => (int) $row->id,
'parent_id' => $row->parent_id !== null ? (int) $row->parent_id : null,
'name' => $row->name,
'audience' => $audiences[$row->id] ?? null,
];
$children[(int) ($row->parent_id ?? 0)][] = (int) $row->id;
}
return ['folders' => $folders, 'children' => $children];
});
}
}

View file

@ -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;
}
}

View file

@ -0,0 +1,67 @@
<?php
namespace Inhaus\Plugins\Downloads\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['folder_id', 'title', 'description', 'created_by', 'updated_by'])]
class Download extends Model
{
protected static function booted(): void
{
// Dateien aller Fassungen mit entfernen.
static::deleting(fn (Download $download) => $download->versions()->get()->each->delete());
}
/**
* @return BelongsTo<DownloadFolder, $this>
*/
public function folder(): BelongsTo
{
return $this->belongsTo(DownloadFolder::class, 'folder_id');
}
/**
* @return BelongsTo<DownloadVersion, $this>
*/
/**
* @return BelongsToMany<User, $this>
*/
public function favoritedBy(): BelongsToMany
{
return $this->belongsToMany(User::class, 'download_favorites')->withPivot('created_at');
}
public function currentVersion(): BelongsTo
{
return $this->belongsTo(DownloadVersion::class, 'current_version_id');
}
/**
* @return HasMany<DownloadVersion, $this>
*/
public function versions(): HasMany
{
return $this->hasMany(DownloadVersion::class)->orderByDesc('version');
}
/**
* @return BelongsTo<User, $this>
*/
public function updater(): BelongsTo
{
return $this->belongsTo(User::class, 'updated_by');
}
public function downloadUrl(?DownloadVersion $version = null): string
{
$version ??= $this->currentVersion;
return route('downloads.download', ['download' => $this->id, 'version' => $version?->version, 'name' => $version?->name ?? 'datei']);
}
}

View file

@ -0,0 +1,51 @@
<?php
namespace Inhaus\Plugins\Downloads\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Inhaus\Plugins\Downloads\FolderTree;
#[Fillable(['parent_id', 'name', 'description', 'sort', 'created_by'])]
class DownloadFolder extends Model
{
protected static function booted(): void
{
static::saved(fn (DownloadFolder $folder) => FolderTree::flush($folder->wasRecentlyCreated || $folder->wasChanged('parent_id')));
static::deleted(fn () => FolderTree::flush(true));
}
/**
* @return array{0: string, 1: int}
*/
public function permissionResource(): array
{
return ['download_folder', $this->id];
}
/**
* @return BelongsTo<DownloadFolder, $this>
*/
public function parent(): BelongsTo
{
return $this->belongsTo(DownloadFolder::class, 'parent_id');
}
/**
* @return HasMany<DownloadFolder, $this>
*/
public function children(): HasMany
{
return $this->hasMany(DownloadFolder::class, 'parent_id')->orderBy('sort')->orderBy('name');
}
/**
* @return HasMany<Download, $this>
*/
public function downloads(): HasMany
{
return $this->hasMany(Download::class, 'folder_id');
}
}

View file

@ -0,0 +1,47 @@
<?php
namespace Inhaus\Plugins\Downloads\Models;
use App\Models\User;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;
/**
* Eine Fassung einer Datei. Die Datei liegt außerhalb von public/ und
* wird nur an Personen ausgeliefert, die den Ordner sehen dürfen.
*/
#[Fillable(['download_id', 'version', 'name', 'path', 'mime', 'size', 'note', 'uploaded_by', 'created_at'])]
class DownloadVersion extends Model
{
public const DISK = 'local';
public const UPDATED_AT = null;
protected static function booted(): void
{
static::deleted(fn (DownloadVersion $version) => Storage::disk(self::DISK)->delete($version->path));
}
/**
* @return BelongsTo<Download, $this>
*/
public function download(): BelongsTo
{
return $this->belongsTo(Download::class);
}
/**
* @return BelongsTo<User, $this>
*/
public function uploader(): BelongsTo
{
return $this->belongsTo(User::class, 'uploaded_by');
}
public function extension(): string
{
return strtoupper(pathinfo($this->name, PATHINFO_EXTENSION));
}
}

View file

@ -0,0 +1,41 @@
<?php
namespace Inhaus\Plugins\Downloads\Policies;
use App\Models\User;
use Inhaus\Plugins\Downloads\FolderTree;
use Inhaus\Plugins\Downloads\Models\DownloadFolder;
/**
* „Downloads verwalten“ gilt für den ganzen Bereich. „Downloads pflegen“ wird je
* Ordner vergeben (meist inkl. Unterordnern) – z. B. pflegt die Personalabteilung
* den Ordner „Personal“.
*/
class DownloadFolderPolicy
{
public function viewAny(User $user): bool
{
return $user->can('downloads.manage') || $user->permissions()->ids('downloads.edit', 'download_folder') !== [];
}
public function view(User $user, DownloadFolder $folder): bool
{
return app(FolderTree::class)->isVisible($folder->id, $user) || $this->update($user, $folder);
}
public function create(User $user, ?DownloadFolder $parent = null): bool
{
return $user->can('downloads.manage') || ($parent !== null && $this->update($user, $parent));
}
/** Dateien hochladen, ändern, löschen; Unterordner anlegen. */
public function update(User $user, DownloadFolder $folder): bool
{
return $user->can('downloads.manage') || $user->can('downloads.edit', ['download_folder', $folder->id]);
}
public function delete(User $user, DownloadFolder $folder): bool
{
return $user->can('downloads.manage') || ($folder->parent_id !== null && $user->can('downloads.edit', ['download_folder', $folder->parent_id]));
}
}