Neues Modul: Qualitätsmanagement
All checks were successful
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 2m46s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 2m51s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 3m2s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 2m55s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 4m15s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 4m16s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 3m44s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 3m46s
CI / Build-Artefakte aktuell (pull_request) Successful in 52s

- Kategorien mit farbigen Ordnerkacheln; Farbe und Symbol je Ordner
  (Auswahl oder eigener Upload, SVG bereinigt), an Unterordner vererbt
- Ordnerseite: Einführungstext, Ansprechpartner (Profilfelder wählbar),
  Unterordner, Liste mit Dokument, Version, Stand, Größe, Aktion
- Einträge: Datei (Lesefassung + bearbeitbare Vorlage), Link,
  Online-Formular; neue Fassungen archivieren die bisherigen
- PDF-Betrachter im Portal (pdf.js)
- Eigene Volltextsuche (PDF, Word, Excel, PowerPoint, OpenDocument)
  mit Textausschnitt; optionale Texterkennung per Tesseract
- Rollen-Ausschluss für das ganze Modul, Pflegerecht qm.manage,
  Zielgruppen je Kategorie
- Vorbereitet: Wiedervorlage, Verantwortliche, Lesebestätigungen
- Abhängigkeit smalot/pdfparser

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 15:50:23 +00:00
parent f78cc96be7
commit b3a057e27c
218 changed files with 13478 additions and 358 deletions

View file

@ -0,0 +1,43 @@
<?php
namespace Inhaus\Plugins\Qm;
/**
* Feste Farbpalette für QM-Ordner – abgestimmt auf gut lesbare weiße Schrift
* (Kontrast ≥ 4,5:1) in hellem und dunklem Modus. Unterordner erben die Farbe.
*/
final class Colors
{
public const DEFAULT = 'blue';
/** Schlüssel => [Bezeichnung, Hex] – die Hex-Werte entsprechen den Tailwind-Klassen im Frontend. */
public const PALETTE = [
'blue' => ['Blau', '#2563eb'],
'sky' => ['Himmelblau', '#0369a1'],
'teal' => ['Petrol', '#0f766e'],
'emerald' => ['Smaragd', '#047857'],
'green' => ['Grün', '#15803d'],
'amber' => ['Bernstein', '#b45309'],
'orange' => ['Orange', '#c2410c'],
'red' => ['Rot', '#dc2626'],
'rose' => ['Rosé', '#e11d48'],
'violet' => ['Violett', '#7c3aed'],
'indigo' => ['Indigo', '#4f46e5'],
'slate' => ['Schiefer', '#475569'],
];
public static function has(?string $key): bool
{
return $key !== null && isset(self::PALETTE[$key]);
}
/**
* Für Filament-Select mit ->allowHtml(): Farbfeld und Name.
*
* @return array<string, string>
*/
public static function options(): array
{
return collect(self::PALETTE)->map(fn (array $color) => '<span style="display:inline-flex;align-items:center;gap:8px"><span style="width:16px;height:16px;border-radius:4px;background:'.$color[1].'"></span>'.e($color[0]).'</span>')->all();
}
}

View file

@ -0,0 +1,125 @@
<?php
namespace Inhaus\Plugins\Qm\Filament\Pages;
use App\Models\Role;
use App\Support\Audit;
use App\Support\Settings;
use BackedEnum;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\HtmlString;
use Inhaus\Plugins\Qm\Presenter;
use Inhaus\Plugins\Qm\QmAccess;
use Inhaus\Plugins\Qm\Text\Ocr;
use UnitEnum;
class QmSettings extends Page
{
protected string $view = 'filament.pages.settings-form';
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedAdjustmentsHorizontal;
protected static string|UnitEnum|null $navigationGroup = 'Qualitätsmanagement';
protected static ?int $navigationSort = 3;
protected static ?string $navigationLabel = 'QM-Einstellungen';
protected static ?string $title = 'QM-Einstellungen';
protected static ?string $slug = 'qm-einstellungen';
/** @var array<string, mixed>|null */
public ?array $data = [];
public static function canAccess(): bool
{
return auth()->user()?->can('qm.manage') ?? false;
}
public function mount(Settings $settings): void
{
$this->form->fill([
'contact_fields' => (array) $settings->get(Presenter::CONTACT_FIELDS, Presenter::DEFAULT_CONTACT_FIELDS),
'excluded_roles' => array_map('strval', (array) $settings->get(QmAccess::EXCLUDED_ROLES, [])),
'ocr_enabled' => (bool) $settings->get(Ocr::SETTING_ENABLED, false),
'ocr_binary' => (string) $settings->get(Ocr::SETTING_BINARY, ''),
]);
}
public function form(Schema $schema): Schema
{
return $schema->statePath('data')->components([
Section::make('Ansprechpartner')
->description('Welche Angaben aus dem Profil bei Ansprechpartnern in den QM-Ordnern erscheinen. Name und Foto werden immer gezeigt.')
->schema([
CheckboxList::make('contact_fields')->hiddenLabel()->columns(3)
->options(fn () => app(Presenter::class)->contactFieldOptions()),
]),
Section::make('Zugang')
->description('Grundsätzlich sehen alle angemeldeten Personen das Qualitätsmanagement; pflegen darf nur, wer das Recht „Qualitätsmanagement pflegen“ hat (ohne Vergabe: die Administration).')
->schema([
Select::make('excluded_roles')->label('Ausgeschlossene Rollen')->multiple()->native(false)
->options(fn () => Role::query()->orderBy('name')->pluck('name', 'id')->mapWithKeys(fn ($name, $id) => [(string) $id => $name])->all())
->helperText('Wer eine dieser Rollen hat, sieht das Modul nicht – weder im Menü noch über Links (z. B. Klient*innen, Gäste). Der Ausschluss geht anderen Rollen vor.'),
]),
Section::make('Texterkennung (OCR) für eingescannte PDFs')
->description('Text aus PDF, Word, Excel und PowerPoint wird immer durchsuchbar gemacht. Eingescannte PDFs ohne Textebene brauchen dafür eine Texterkennung auf dem Server.')
->columns(2)
->schema([
Text::make(fn () => $this->ocrStatus())->columnSpanFull(),
Toggle::make('ocr_enabled')->label('Texterkennung verwenden')
->helperText('Läuft im Hintergrund (Hintergrundaufgaben), einige Dateien je Durchgang.'),
TextInput::make('ocr_binary')->label('Pfad zu Tesseract')->placeholder('tesseract')->maxLength(200)
->regex('#^(/[\w./-]+|[\w.-]+)$#')
->helperText('Nur nötig, wenn das Programm nicht im Suchpfad liegt, z. B. /usr/bin/tesseract.'),
]),
]);
}
public function save(Settings $settings): void
{
$data = $this->form->getState();
$options = app(Presenter::class)->contactFieldOptions();
$settings->setMany([
Presenter::CONTACT_FIELDS => array_values(array_intersect((array) $data['contact_fields'], array_keys($options))),
QmAccess::EXCLUDED_ROLES => array_values(array_map('intval', (array) $data['excluded_roles'])),
Ocr::SETTING_ENABLED => (bool) $data['ocr_enabled'],
Ocr::SETTING_BINARY => trim((string) $data['ocr_binary']),
]);
Audit::log('qm.settings_saved', ['excluded_roles' => count((array) $data['excluded_roles'])]);
Notification::make()->success()->title('Gespeichert')->send();
}
private function ocrStatus(): HtmlString
{
$status = app(Ocr::class)->status();
$pending = DB::table('qm_files')->where('text_status', 'needs_ocr')->whereNull('archived_at')->count();
$ok = fn (bool $v) => $v ? '<span style="color:rgb(22 163 74)">✔</span>' : '<span style="color:rgb(220 38 38)">✘</span>';
return new HtmlString(
'<div style="display:grid;gap:4px;font-size:13px">'
.'<div>'.$ok($status['exec']).' Programme aufrufen erlaubt (PHP-Funktion proc_open)</div>'
.'<div>'.$ok($status['tesseract'] !== null).' Tesseract: '.e($status['tesseract'] ?? 'nicht gefunden')
.($status['languages'] ? ' · Sprachen: '.e(implode(', ', array_slice($status['languages'], 0, 8))) : '').'</div>'
.'<div>'.$ok($status['rasterizer'] !== null).' PDF-Seiten in Bilder umwandeln: '.e($status['rasterizer'] ?? 'weder pdftoppm noch Imagick mit PDF-Unterstützung').'</div>'
.'<div style="margin-top:4px">'.$pending.' eingescannte Datei(en) warten auf Texterkennung.</div>'
.'<div style="margin-top:6px;opacity:.75">Einrichtung auf eigenem Server (Debian/Ubuntu): <code>apt install tesseract-ocr tesseract-ocr-deu poppler-utils</code>. Ein Apache-Modul gibt es dafür nicht; Tesseract ist ein eigenständiges Programm, das PHP aufruft.</div>'
.'</div>'
);
}
}

View file

@ -0,0 +1,18 @@
<?php
namespace Inhaus\Plugins\Qm\Filament\Resources\QmCategories\Pages;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ManageRecords;
use Inhaus\Plugins\Qm\Filament\Resources\QmCategories\QmCategoryResource;
use Inhaus\Plugins\Qm\QmTree;
class ManageQmCategories extends ManageRecords
{
protected static string $resource = QmCategoryResource::class;
protected function getHeaderActions(): array
{
return [CreateAction::make()->label('Kategorie anlegen')->after(fn () => QmTree::flush())];
}
}

View file

@ -0,0 +1,73 @@
<?php
namespace Inhaus\Plugins\Qm\Filament\Resources\QmCategories;
use App\Filament\Components\AudienceSection;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Inhaus\Plugins\Qm\Filament\Resources\QmCategories\Pages\ManageQmCategories;
use Inhaus\Plugins\Qm\Models\QmCategory;
use Inhaus\Plugins\Qm\QmTree;
use UnitEnum;
/**
* Kategorien der QM-Startseite (Überschrift mit Trennlinie über den Ordnerkacheln).
*/
class QmCategoryResource extends Resource
{
protected static ?string $model = QmCategory::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedRectangleStack;
protected static string|UnitEnum|null $navigationGroup = 'Qualitätsmanagement';
protected static ?int $navigationSort = 2;
protected static ?string $modelLabel = 'QM-Kategorie';
protected static ?string $pluralModelLabel = 'Kategorien';
protected static ?string $slug = 'qm-kategorien';
public static function canAccess(): bool
{
return auth()->user()?->can('qm.manage') ?? false;
}
public static function form(Schema $schema): Schema
{
return $schema->columns(2)->components([
TextInput::make('name')->label('Name')->required()->maxLength(120)->placeholder('z. B. Allgemein'),
TextInput::make('sort')->label('Reihenfolge')->numeric()->default(0),
AudienceSection::make('qm_category', 'Wer die Kategorie samt allen Ordnern sieht. Leer lassen = alle, die das QM-Modul sehen.')->columnSpanFull()->collapsed(),
]);
}
public static function table(Table $table): Table
{
return $table
->defaultSort('sort')
->reorderable('sort')
->modifyQueryUsing(fn ($query) => $query->withCount('folders'))
->columns([
TextColumn::make('name')->label('Name')->weight('medium'),
TextColumn::make('folders_count')->label('Ordner'),
])
->recordActions([
EditAction::make()->after(fn () => QmTree::flush()),
DeleteAction::make()->modalDescription('Die Ordner bleiben erhalten und erscheinen unter „Weitere“.'),
]);
}
public static function getPages(): array
{
return ['index' => ManageQmCategories::route('/')];
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace Inhaus\Plugins\Qm\Filament\Resources\QmFolders\Pages;
use App\Support\Theme\SvgSanitizer;
use Filament\Resources\Pages\CreateRecord;
use Inhaus\Plugins\Qm\Filament\Resources\QmFolders\QmFolderResource;
use Inhaus\Plugins\Qm\QmTree;
class CreateQmFolder extends CreateRecord
{
protected static string $resource = QmFolderResource::class;
protected function mutateFormDataBeforeCreate(array $data): array
{
$data['created_by'] = auth()->id();
if (filled($data['parent_id'] ?? null)) {
$data['category_id'] = null;
}
return $data;
}
protected function afterCreate(): void
{
SvgSanitizer::sanitizeFile($this->record->icon_path);
QmTree::flush();
}
protected function getRedirectUrl(): string
{
return QmFolderResource::getUrl('index');
}
}

View file

@ -0,0 +1,49 @@
<?php
namespace Inhaus\Plugins\Qm\Filament\Resources\QmFolders\Pages;
use App\Support\Theme\SvgSanitizer;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Storage;
use Inhaus\Plugins\Qm\Filament\Resources\QmFolders\QmFolderResource;
use Inhaus\Plugins\Qm\QmTree;
class EditQmFolder extends EditRecord
{
protected static string $resource = QmFolderResource::class;
private ?string $previousIcon = null;
protected function mutateFormDataBeforeSave(array $data): array
{
$this->previousIcon = $this->record->icon_path;
if (filled($data['parent_id'] ?? null)) {
$data['category_id'] = null;
}
return $data;
}
protected function afterSave(): void
{
if ($this->previousIcon && $this->previousIcon !== $this->record->icon_path) {
Storage::disk('uploads')->delete($this->previousIcon);
}
SvgSanitizer::sanitizeFile($this->record->icon_path);
QmTree::flush();
}
protected function getHeaderActions(): array
{
return [
Action::make('open')->label('Im Portal ansehen')->icon(Heroicon::OutlinedEye)->color('gray')
->url(fn () => route('qm.folder', $this->record))->openUrlInNewTab(),
DeleteAction::make()->visible(fn () => ! $this->record->entries()->exists() && ! $this->record->children()->exists()),
];
}
}

View file

@ -0,0 +1,34 @@
<?php
namespace Inhaus\Plugins\Qm\Filament\Resources\QmFolders\Pages;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
use Filament\Support\Icons\Heroicon;
use Illuminate\Database\Eloquent\Builder;
use Inhaus\Plugins\Qm\Filament\Resources\QmFolders\QmFolderResource;
use Inhaus\Plugins\Qm\QmTree;
class ListQmFolders extends ListRecords
{
protected static string $resource = QmFolderResource::class;
protected function getHeaderActions(): array
{
return [
Action::make('portal')->label('QM im Portal')->icon(Heroicon::OutlinedEye)->color('gray')->url('/qm')->openUrlInNewTab(),
CreateAction::make()->label('Ordner anlegen'),
];
}
/**
* In Baumreihenfolge: jeder Ordner direkt unter seinem übergeordneten.
*/
protected function applySortingToTableQuery(Builder $query): Builder
{
$order = array_keys(app(QmTree::class)->options());
return $order === [] ? $query : $query->orderByRaw('FIELD(id, '.implode(',', array_map('intval', $order)).')');
}
}

View file

@ -0,0 +1,148 @@
<?php
namespace Inhaus\Plugins\Qm\Filament\Resources\QmFolders;
use App\Support\Icons;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\HtmlString;
use Inhaus\Plugins\Qm\Colors;
use Inhaus\Plugins\Qm\Filament\Resources\QmFolders\Pages\CreateQmFolder;
use Inhaus\Plugins\Qm\Filament\Resources\QmFolders\Pages\EditQmFolder;
use Inhaus\Plugins\Qm\Filament\Resources\QmFolders\Pages\ListQmFolders;
use Inhaus\Plugins\Qm\Models\QmCategory;
use Inhaus\Plugins\Qm\Models\QmFolder;
use Inhaus\Plugins\Qm\QmTree;
use UnitEnum;
/**
* QM-Ordner: Struktur, Farbe und Symbol (werden vererbt), Einführungstext und
* Ansprechpartner. Dokumente pflegt das QM-Team direkt im Portal.
*/
class QmFolderResource extends Resource
{
protected static ?string $model = QmFolder::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedFolder;
protected static string|UnitEnum|null $navigationGroup = 'Qualitätsmanagement';
protected static ?int $navigationSort = 1;
protected static ?string $modelLabel = 'QM-Ordner';
protected static ?string $pluralModelLabel = 'Ordner';
protected static ?string $slug = 'qm-ordner';
public static function canAccess(): bool
{
return auth()->user()?->can('qm.manage') ?? false;
}
public static function form(Schema $schema): Schema
{
return $schema->columns(1)->components([
Section::make('Ordner')->columns(2)->schema([
TextInput::make('name')->label('Name')->required()->maxLength(120),
Select::make('parent_id')->label('Übergeordneter Ordner')->placeholder('– oberste Ebene –')->searchable()->native(false)->live()
->options(fn (?QmFolder $record) => collect(app(QmTree::class)->options())
->except($record ? [$record->id, ...app(QmTree::class)->descendantIds([$record->id])] : [])->all()),
Select::make('category_id')->label('Kategorie auf der QM-Startseite')->native(false)
->options(fn () => QmCategory::query()->orderBy('sort')->pluck('name', 'id')->all())
->required(fn (Get $get) => blank($get('parent_id')))
->visible(fn (Get $get) => blank($get('parent_id')))
->helperText('Nur für Ordner der obersten Ebene. Kategorien legen Sie unter „Kategorien“ an.'),
TextInput::make('sort')->label('Reihenfolge')->numeric()->default(0),
]),
Section::make('Farbe und Symbol')
->description('Unterordner übernehmen Farbe und Symbol, solange dort nichts eigenes gewählt ist.')
->columns(2)
->schema([
Select::make('color')->label('Farbe')->native(false)->allowHtml()
->options(Colors::options())
->placeholder(fn (Get $get) => blank($get('parent_id')) ? 'Standard (Blau)' : 'Vom übergeordneten Ordner übernehmen'),
Select::make('icon')->label('Symbol')->native(false)->allowHtml()->searchable()
->options(Icons::options())
->getSearchResultsUsing(fn (string $search) => Icons::search($search))
->getOptionLabelUsing(fn (?string $value) => $value ? Icons::option($value) : null)
->placeholder(fn (Get $get) => blank($get('parent_id')) ? 'Ordner' : 'Vom übergeordneten Ordner übernehmen')
->helperText('Alle 1.800+ Symbole über die Suche (englische Namen).'),
FileUpload::make('icon_path')->label('Oder eigenes Symbol hochladen')
->disk('uploads')->directory('qm-icons')->visibility('public')
->acceptedFileTypes(['image/svg+xml', 'image/png', 'image/webp', 'image/jpeg'])->maxSize(1024)
->helperText('SVG (empfohlen), PNG, WebP oder JPG, quadratisch. Ersetzt das Symbol aus der Auswahl.')
->live(),
Toggle::make('icon_mono')->label('Eigenes Symbol einfarbig darstellen')->default(true)
->helperText('Wie die mitgelieferten Symbole: weiß auf der Kachel. Für farbige Logos ausschalten.')
->visible(fn (Get $get) => filled($get('icon_path'))),
]),
Section::make('Einführungstext')->schema([
RichEditor::make('intro')->hiddenLabel()
->toolbarButtons(['bold', 'italic', 'link', 'bulletList', 'orderedList', 'h3', 'blockquote', 'undo', 'redo']),
]),
Section::make('Ansprechpartner')
->description('Welche Angaben aus dem Profil erscheinen (Telefon, E-Mail …), legen Sie unter „QM-Einstellungen“ fest.')
->schema([
Select::make('contacts')->hiddenLabel()->multiple()->searchable()->preload()
->relationship('contacts', 'name', fn ($query) => $query->where('is_active', true)->orderBy('last_name'))
->getOptionLabelFromRecordUsing(fn ($record) => $record->name.($record->job_title ? ' – '.$record->job_title : '')),
]),
]);
}
public static function table(Table $table): Table
{
$tree = app(QmTree::class);
return $table
->modifyQueryUsing(fn ($query) => $query->withCount('entries'))
->defaultSort('name')
->paginated(false)
->columns([
TextColumn::make('name')->label('Ordner')->weight('medium')->searchable()
->formatStateUsing(function (string $state, QmFolder $record) use ($tree) {
$node = $tree->folder($record->id);
$depth = max(0, count($tree->path($record->id)) - 1);
$hex = Colors::PALETTE[$node['color'] ?? Colors::DEFAULT][1];
return new HtmlString(str_repeat('<span style="display:inline-block;width:20px"></span>', $depth)
.'<span style="display:inline-block;width:10px;height:10px;border-radius:3px;margin-right:8px;background:'.$hex.'"></span>'.e($state));
}),
TextColumn::make('category.name')->label('Kategorie')->placeholder('–'),
TextColumn::make('entries_count')->label('Einträge'),
])
->recordActions([
Action::make('open')->label('Im Portal')->icon(Heroicon::OutlinedArrowTopRightOnSquare)->iconButton()
->url(fn (QmFolder $record) => route('qm.folder', $record))->openUrlInNewTab(),
EditAction::make(),
DeleteAction::make()->visible(fn (QmFolder $record) => $record->entries_count === 0 && ! $record->children()->exists()),
]);
}
public static function getPages(): array
{
return [
'index' => ListQmFolders::route('/'),
'create' => CreateQmFolder::route('/neu'),
'edit' => EditQmFolder::route('/{record}/edit'),
];
}
}

View file

@ -0,0 +1,253 @@
<?php
namespace Inhaus\Plugins\Qm\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Support\Audit;
use App\Support\RichText;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Qm\Library;
use Inhaus\Plugins\Qm\Models\QmEntry;
use Inhaus\Plugins\Qm\Models\QmFile;
use Inhaus\Plugins\Qm\Models\QmFolder;
use Inhaus\Plugins\Qm\Presenter;
use Inhaus\Plugins\Qm\QmAccess;
use Inhaus\Plugins\Qm\QmTree;
use Inhaus\Plugins\Qm\Search;
use Symfony\Component\HttpFoundation\Response as HttpResponse;
class QmController extends Controller
{
public function __construct(
private readonly QmTree $tree,
private readonly Presenter $presenter,
private readonly QmAccess $access,
) {}
public function index(Request $request): Response
{
$counts = $this->entryCounts();
return Inertia::render('qm::Index', [
'categories' => collect($this->tree->categories($request->user()))->map(fn (array $category) => [
'id' => $category['id'],
'name' => $category['name'],
'folders' => array_map(fn (int $id) => $this->presenter->tile($id, $counts), $category['folders']),
])->values(),
'canManage' => $this->access->canManage($request->user()),
'adminUrl' => $this->access->canManage($request->user()) ? url('/admin/qm-ordner') : null,
]);
}
public function folder(Request $request, QmFolder $folder): Response
{
abort_unless($this->tree->isVisible($folder->id, $request->user()), 404);
$counts = $this->entryCounts();
$canManage = $this->access->canManage($request->user());
$entries = $folder->entries()->with(['readingFile', 'editableFile'])->orderBy('sort')->orderBy('title')->get();
$node = $this->tree->folder($folder->id);
return Inertia::render('qm::Folder', [
'folder' => [
'id' => $folder->id,
'name' => $folder->name,
'color' => $node['color'],
'icon' => $node['icon'],
'intro' => app(RichText::class)->sanitize($folder->intro),
'contacts' => $this->presenter->contacts($folder->contacts()->get(), $request->user()),
],
'breadcrumbs' => array_map(fn (array $f) => ['id' => $f['id'], 'name' => $f['name'], 'color' => $f['color']], array_slice($this->tree->path($folder->id), 0, -1)),
'children' => array_map(fn (int $id) => $this->presenter->tile($id, $counts), $this->tree->childIds($folder->id)),
'entries' => $entries->map(fn (QmEntry $entry) => $this->presenter->entry($entry)),
'canManage' => $canManage,
'forms' => $canManage ? $this->formOptions() : [],
'maxUploadMb' => (int) floor(min(Library::MAX_KB / 1024, self::phpUploadLimitMb())),
'adminUrl' => $canManage ? url('/admin/qm-ordner/'.$folder->id.'/edit') : null,
]);
}
public function search(Request $request, Search $search): Response
{
$query = trim((string) $request->query('q', ''));
return Inertia::render('qm::Search', [
'query' => $query,
'results' => $query === '' ? [] : $search->run($query, $request->user())->map(fn (array $hit) => [
...$this->presenter->entry($hit['entry'], withFolder: true),
'snippet' => $hit['snippet'],
'in_content' => $hit['in_content'],
])->values(),
]);
}
/**
* Datei zum Lesen im Portal (PDF-Betrachter bzw. Bild).
*/
public function view(Request $request, QmEntry $entry): Response|RedirectResponse
{
abort_unless($this->tree->isVisible($entry->folder_id, $request->user()), 404);
$entry->load(['readingFile', 'editableFile']);
$file = $entry->readingFile ?? $entry->editableFile;
abort_unless($file, 404);
if (! $file->isViewable()) {
return redirect($file->url());
}
return Inertia::render('qm::Viewer', [
'entry' => $this->presenter->entry($entry, withFolder: true),
'file' => ['url' => $file->url(inline: true), 'kind' => $file->mime === 'application/pdf' ? 'pdf' : 'image', 'name' => $file->name],
'query' => (string) $request->query('suche', ''),
]);
}
public function file(Request $request, QmFile $file): HttpResponse
{
$entry = $file->entry;
abort_unless($entry && $this->tree->isVisible($entry->folder_id, $request->user()), 404);
// Archivierte Fassungen sieht nur das QM-Team.
abort_if($file->archived_at && ! $this->access->canManage($request->user()), 404);
$headers = ['X-Content-Type-Options' => 'nosniff', 'Cache-Control' => 'private, max-age=300'];
if ($request->boolean('lesen') && $file->isViewable()) {
// Bilder abgeschottet; PDFs ohne sandbox, sonst blockiert Chrome seinen PDF-Betrachter.
return Storage::disk(QmFile::DISK)->response($file->path, $file->name, [
...$headers,
'Content-Type' => $file->mime,
...($file->mime === 'application/pdf' ? [] : ['Content-Security-Policy' => "default-src 'none'; sandbox"]),
]);
}
return Storage::disk(QmFile::DISK)->download($file->path, $file->name, [...$headers, 'Content-Type' => $file->mime ?: 'application/octet-stream']);
}
public function store(Request $request, QmFolder $folder, Library $library): RedirectResponse
{
$this->authorizeManage($request);
$data = $this->validated($request, null);
$entry = $library->create($folder, $data, $request->file('reading'), $request->file('editable'), $request->user());
Audit::log('qm.entry_created', ['entry' => $entry->id, 'title' => $entry->title, 'folder' => $folder->id]);
return back()->with('status', 'Eintrag „'.$entry->title.'“ angelegt.');
}
public function update(Request $request, QmEntry $entry, Library $library): RedirectResponse
{
$this->authorizeManage($request);
$data = $this->validated($request, $entry);
$library->update($entry, $data, $request->file('reading'), $request->file('editable'), $request->boolean('remove_editable'), $request->user());
Audit::log('qm.entry_updated', ['entry' => $entry->id, 'title' => $entry->title, 'new_version' => $request->hasFile('reading') || $request->hasFile('editable')]);
return back()->with('status', $request->hasFile('reading') || $request->hasFile('editable') ? 'Neue Fassung gespeichert – die bisherige liegt im Archiv.' : 'Gespeichert.');
}
public function destroy(Request $request, QmEntry $entry): RedirectResponse
{
$this->authorizeManage($request);
$title = $entry->title;
$entry->delete();
Audit::log('qm.entry_deleted', ['entry' => $entry->id, 'title' => $title]);
return back()->with('status', '„'.$title.'“ gelöscht.');
}
public function archive(Request $request, QmEntry $entry): JsonResponse
{
$this->authorizeManage($request);
return response()->json(['files' => $entry->files()->with('uploader:id,first_name,last_name,name')->orderByDesc('created_at')->orderByDesc('id')->get()
->map(fn (QmFile $file) => [
'id' => $file->id,
'kind' => $file->kind,
'name' => $file->name,
'version' => $file->version,
'valid_from' => $file->valid_from?->toDateString(),
'size' => $file->size,
'uploaded_at' => $file->created_at?->toIso8601String(),
'uploader' => $file->uploader?->name,
'archived' => $file->archived_at !== null,
'url' => $file->url(),
])]);
}
/**
* @return array<string, mixed>
*/
private function validated(Request $request, ?QmEntry $entry): array
{
$type = $entry?->type ?? $request->input('type');
$fileRule = ['nullable', 'file', 'max:'.Library::MAX_KB, 'extensions:'.implode(',', Library::EXTENSIONS)];
return $request->validate([
'type' => [$entry ? 'nullable' : 'required', Rule::in([QmEntry::FILE, QmEntry::LINK, QmEntry::FORM])],
'title' => ['required', 'string', 'max:250'],
'description' => ['nullable', 'string', 'max:1000'],
'version' => ['nullable', 'string', 'max:30'],
'valid_from' => ['nullable', 'date'],
'url' => [Rule::requiredIf($type === QmEntry::LINK), 'nullable', 'string', 'max:1000', 'regex:#^(https?://|/)#i'],
'form_id' => [Rule::requiredIf($type === QmEntry::FORM), 'nullable', 'integer', Rule::exists('forms', 'id')],
'reading' => [...$fileRule, Rule::requiredIf($type === QmEntry::FILE && ! $entry && ! $request->hasFile('editable'))],
'editable' => $fileRule,
], ['url.regex' => 'Bitte eine Adresse angeben, die mit https:// oder / beginnt.', 'reading.required' => 'Bitte eine Datei auswählen.'], [
'title' => 'Titel', 'version' => 'Version', 'valid_from' => 'Stand', 'url' => 'Adresse', 'form_id' => 'Formular',
'reading' => 'Datei', 'editable' => 'Bearbeitbare Vorlage',
]) + ['type' => $type];
}
private function authorizeManage(Request $request): void
{
abort_unless($this->access->canManage($request->user()), 403);
}
/**
* @return array<int, int> Ordner => Anzahl Einträge
*/
private function entryCounts(): array
{
return DB::table('qm_entries')->selectRaw('folder_id, count(*) as c')->groupBy('folder_id')->pluck('c', 'folder_id')->map(fn ($c) => (int) $c)->all();
}
/**
* @return list<array{value: int, label: string}>
*/
private function formOptions(): array
{
if (! DB::getSchemaBuilder()->hasTable('forms')) {
return [];
}
return DB::table('forms')->orderBy('title')->get(['id', 'title'])->map(fn ($f) => ['value' => (int) $f->id, 'label' => $f->title])->all();
}
private static function phpUploadLimitMb(): float
{
$bytes = function (string $value): float {
$value = trim($value);
$unit = strtolower(substr($value, -1));
$number = (float) $value;
return match ($unit) {
'g' => $number * 1024 ** 3,
'm' => $number * 1024 ** 2,
'k' => $number * 1024,
default => $number,
};
};
$limits = array_filter([$bytes((string) ini_get('upload_max_filesize')), $bytes((string) ini_get('post_max_size'))]);
return $limits === [] ? 100 : min($limits) / 1024 / 1024;
}
}

View file

@ -0,0 +1,21 @@
<?php
namespace Inhaus\Plugins\Qm\Http;
use Closure;
use Illuminate\Http\Request;
use Inhaus\Plugins\Qm\QmAccess;
use Symfony\Component\HttpFoundation\Response;
/**
* Ausgeschlossene Rollen (z. B. Klient*innen) sehen das QM-Modul nicht – auch nicht über Links.
*/
class EnsureQmAccess
{
public function handle(Request $request, Closure $next): Response
{
abort_unless(app(QmAccess::class)->allows($request->user()), 404);
return $next($request);
}
}

View file

@ -0,0 +1,55 @@
<?php
namespace Inhaus\Plugins\Qm;
use Illuminate\Support\Facades\Storage;
use Inhaus\Plugins\Qm\Models\QmFile;
use Inhaus\Plugins\Qm\Text\Ocr;
use Inhaus\Plugins\Qm\Text\TextExtractor;
use Throwable;
/**
* Macht den Inhalt von QM-Dateien durchsuchbar: Textauszug beim Hochladen,
* Texterkennung für eingescannte PDFs im Hintergrund (wenn eingerichtet).
*/
class Indexer
{
public function __construct(private readonly TextExtractor $extractor, private readonly Ocr $ocr) {}
public function index(QmFile $file): void
{
$path = Storage::disk(QmFile::DISK)->path($file->path);
$result = $this->extractor->extract($path, pathinfo($file->name, PATHINFO_EXTENSION));
// PDF ohne Text: vermutlich eingescannt → Texterkennung vormerken.
$status = $result['status'] === 'empty' && $file->mime === 'application/pdf' ? 'needs_ocr' : $result['status'];
$file->forceFill(['text' => $result['text'], 'text_status' => $status])->save();
}
/**
* Hintergrundaufgabe: vorgemerkte Scans erkennen. Gibt die Anzahl bearbeiteter Dateien zurück.
*/
public function processOcr(int $limit = 5): int
{
if (! $this->ocr->enabled() || ! $this->ocr->available()) {
return 0;
}
$done = 0;
foreach (QmFile::query()->where('text_status', 'needs_ocr')->whereNull('archived_at')->limit($limit)->get() as $file) {
try {
$text = $this->ocr->recognize(Storage::disk(QmFile::DISK)->path($file->path));
$file->forceFill(['text' => $text !== '' ? $text : null, 'text_status' => $text !== '' ? 'ocr' : 'empty'])->save();
} catch (Throwable $e) {
logger()->warning("QM-Texterkennung für {$file->name} fehlgeschlagen: ".$e->getMessage());
$file->forceFill(['text_status' => 'failed'])->save();
}
$done++;
}
return $done;
}
}

View file

@ -0,0 +1,122 @@
<?php
namespace Inhaus\Plugins\Qm;
use App\Models\User;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inhaus\Plugins\Qm\Models\QmEntry;
use Inhaus\Plugins\Qm\Models\QmFile;
use Inhaus\Plugins\Qm\Models\QmFolder;
/**
* Einträge anlegen, ändern und neue Fassungen hochladen. Eine neue Fassung
* schiebt die bisherigen Dateien ins Archiv – nichts geht verloren.
*/
class Library
{
/** Erlaubte Dateitypen (Lesefassung vor allem PDF, Vorlagen Office). */
public const EXTENSIONS = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'ods', 'odp', 'rtf', 'txt', 'csv', 'png', 'jpg', 'jpeg', 'gif', 'webp', 'zip'];
public const MAX_KB = 102400;
public function __construct(private readonly Indexer $indexer) {}
/**
* @param array{type: string, title: string, description?: ?string, version?: ?string, valid_from?: ?string, url?: ?string, form_id?: ?int} $data
*/
public function create(QmFolder $folder, array $data, ?UploadedFile $reading, ?UploadedFile $editable, User $user): QmEntry
{
return DB::transaction(function () use ($folder, $data, $reading, $editable, $user) {
$entry = $folder->entries()->create([
...$this->attributes($data),
'created_by' => $user->id,
'updated_by' => $user->id,
]);
if ($entry->type === QmEntry::FILE) {
$this->storeFiles($entry, $reading, $editable, $user);
}
return $entry;
});
}
/**
* Angaben ändern; mit Datei(en) = neue Fassung (bisherige ins Archiv).
*
* @param array<string, mixed> $data
*/
public function update(QmEntry $entry, array $data, ?UploadedFile $reading, ?UploadedFile $editable, bool $removeEditable, User $user): QmEntry
{
return DB::transaction(function () use ($entry, $data, $reading, $editable, $removeEditable, $user) {
$entry->update([...$this->attributes([...$data, 'type' => $entry->type]), 'updated_by' => $user->id]);
if ($entry->type !== QmEntry::FILE) {
return $entry;
}
if ($reading || $editable) {
$this->storeFiles($entry, $reading, $editable, $user);
} else {
// Nur Angaben korrigiert (z. B. Tippfehler in der Version): aktuelle Dateien anpassen.
$entry->files()->whereNull('archived_at')->update(['version' => $entry->version, 'valid_from' => $entry->valid_from]);
}
if ($removeEditable && ! $editable) {
$entry->files()->where('kind', QmFile::EDITABLE)->whereNull('archived_at')->update(['archived_at' => now()]);
}
return $entry->refresh();
});
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function attributes(array $data): array
{
$type = $data['type'];
return [
'type' => $type,
'title' => trim((string) $data['title']),
'description' => filled($data['description'] ?? null) ? trim((string) $data['description']) : null,
'version' => filled($data['version'] ?? null) ? trim((string) $data['version']) : null,
'valid_from' => filled($data['valid_from'] ?? null) ? Carbon::parse($data['valid_from'])->toDateString() : now()->toDateString(),
'url' => $type === QmEntry::LINK ? trim((string) $data['url']) : null,
'form_id' => $type === QmEntry::FORM ? (int) $data['form_id'] : null,
];
}
private function storeFiles(QmEntry $entry, ?UploadedFile $reading, ?UploadedFile $editable, User $user): void
{
foreach ([QmFile::READING => $reading, QmFile::EDITABLE => $editable] as $kind => $upload) {
if (! $upload) {
continue;
}
$entry->files()->where('kind', $kind)->whereNull('archived_at')->update(['archived_at' => now()]);
$name = Str::limit(preg_replace('/[^\pL\pN ._()\-]+/u', '_', $upload->getClientOriginalName()) ?: 'datei', 200, '');
$extension = strtolower(pathinfo($name, PATHINFO_EXTENSION));
$file = $entry->files()->create([
'kind' => $kind,
'version' => $entry->version,
'valid_from' => $entry->valid_from,
'name' => $name,
'path' => $upload->storeAs('qm/'.$entry->id, Str::random(40).($extension ? '.'.$extension : ''), QmFile::DISK),
'mime' => $upload->getMimeType(),
'size' => $upload->getSize(),
'uploaded_by' => $user->id,
'created_at' => now(),
]);
$this->indexer->index($file);
}
}
}

View file

@ -0,0 +1,29 @@
<?php
namespace Inhaus\Plugins\Qm\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Inhaus\Plugins\Qm\QmTree;
/**
* Kategorie auf der QM-Startseite (Überschrift mit Trennlinie über den Ordnerkacheln).
*/
#[Fillable(['name', 'sort'])]
class QmCategory extends Model
{
protected static function booted(): void
{
static::saved(fn () => QmTree::flush());
static::deleted(fn () => QmTree::flush());
}
/**
* @return HasMany<QmFolder, $this>
*/
public function folders(): HasMany
{
return $this->hasMany(QmFolder::class, 'category_id');
}
}

View file

@ -0,0 +1,66 @@
<?php
namespace Inhaus\Plugins\Qm\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 Illuminate\Database\Eloquent\Relations\HasOne;
/**
* Ein Eintrag in einem QM-Ordner: Datei (mit Lesefassung und optional bearbeitbarer
* Vorlage), Link oder Online-Formular. „Stand“ = valid_from.
*/
#[Fillable(['folder_id', 'type', 'title', 'description', 'version', 'valid_from', 'url', 'form_id', 'sort', 'created_by', 'updated_by'])]
class QmEntry extends Model
{
public const FILE = 'file';
public const LINK = 'link';
public const FORM = 'form';
protected static function booted(): void
{
// Dateien mitlöschen (die Datenbank löscht die Zeilen, hier auch die Dateien).
static::deleting(fn (QmEntry $entry) => $entry->files()->get()->each->delete());
}
protected function casts(): array
{
return ['valid_from' => 'date', 'review_due_at' => 'date', 'requires_acknowledgement' => 'boolean'];
}
/**
* @return BelongsTo<QmFolder, $this>
*/
public function folder(): BelongsTo
{
return $this->belongsTo(QmFolder::class);
}
/**
* @return HasMany<QmFile, $this>
*/
public function files(): HasMany
{
return $this->hasMany(QmFile::class, 'entry_id');
}
/**
* @return HasOne<QmFile, $this>
*/
public function readingFile(): HasOne
{
return $this->hasOne(QmFile::class, 'entry_id')->where('kind', QmFile::READING)->whereNull('archived_at');
}
/**
* @return HasOne<QmFile, $this>
*/
public function editableFile(): HasOne
{
return $this->hasOne(QmFile::class, 'entry_id')->where('kind', QmFile::EDITABLE)->whereNull('archived_at');
}
}

View file

@ -0,0 +1,71 @@
<?php
namespace Inhaus\Plugins\Qm\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 Datei eines QM-Eintrags. Aktuelle Fassung: archived_at = null.
* Frühere Fassungen bleiben im Archiv (Nachvollziehbarkeit).
*/
#[Fillable(['entry_id', 'kind', 'version', 'valid_from', 'name', 'path', 'mime', 'size', 'text', 'text_status', 'archived_at', 'uploaded_by', 'created_at'])]
class QmFile extends Model
{
public const DISK = 'local';
public const READING = 'reading';
public const EDITABLE = 'editable';
public const UPDATED_AT = null;
/** Im Browser lesbar (eigener Betrachter). */
public const VIEWABLE = ['application/pdf', 'image/jpeg', 'image/png', 'image/gif', 'image/webp'];
protected $hidden = ['text'];
protected static function booted(): void
{
static::deleted(fn (QmFile $file) => Storage::disk(self::DISK)->delete($file->path));
}
protected function casts(): array
{
return ['valid_from' => 'date', 'archived_at' => 'datetime', 'created_at' => 'datetime'];
}
/**
* @return BelongsTo<QmEntry, $this>
*/
public function entry(): BelongsTo
{
return $this->belongsTo(QmEntry::class, 'entry_id');
}
/**
* @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));
}
public function isViewable(): bool
{
return in_array($this->mime, self::VIEWABLE, true);
}
public function url(bool $inline = false): string
{
return route('qm.file', ['file' => $this->id, 'name' => $this->name]).($inline ? '?lesen=1' : '');
}
}

View file

@ -0,0 +1,73 @@
<?php
namespace Inhaus\Plugins\Qm\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;
use Illuminate\Support\Facades\Storage;
use Inhaus\Plugins\Qm\QmTree;
#[Fillable(['category_id', 'parent_id', 'name', 'color', 'icon', 'icon_path', 'icon_mono', 'intro', 'sort', 'created_by'])]
class QmFolder extends Model
{
protected static function booted(): void
{
static::saved(fn () => QmTree::flush());
static::deleted(function (QmFolder $folder) {
if ($folder->icon_path) {
Storage::disk('uploads')->delete($folder->icon_path);
}
QmTree::flush();
});
}
protected function casts(): array
{
return ['icon_mono' => 'boolean'];
}
/**
* @return BelongsTo<QmCategory, $this>
*/
public function category(): BelongsTo
{
return $this->belongsTo(QmCategory::class);
}
/**
* @return BelongsTo<QmFolder, $this>
*/
public function parent(): BelongsTo
{
return $this->belongsTo(self::class, 'parent_id');
}
/**
* @return HasMany<QmFolder, $this>
*/
public function children(): HasMany
{
return $this->hasMany(self::class, 'parent_id');
}
/**
* @return HasMany<QmEntry, $this>
*/
public function entries(): HasMany
{
return $this->hasMany(QmEntry::class, 'folder_id');
}
/**
* @return BelongsToMany<User, $this>
*/
public function contacts(): BelongsToMany
{
return $this->belongsToMany(User::class, 'qm_folder_contacts', 'folder_id', 'user_id')->withPivot('sort')->orderByPivot('sort');
}
}

View file

@ -0,0 +1,159 @@
<?php
namespace Inhaus\Plugins\Qm;
use App\Models\User;
use App\Support\ProfileFields;
use App\Support\Settings;
use Inhaus\Plugins\Qm\Models\QmEntry;
/**
* Daten für das Portal: Ordnerkacheln, Einträge und Ansprechpartner.
*/
class Presenter
{
public const CONTACT_FIELDS = 'qm.contact_fields';
/** Kernfelder des Profils, die bei Ansprechpartnern erscheinen können. */
public const CORE_FIELDS = [
'job_title' => 'Funktion',
'department' => 'Abteilung',
'location' => 'Standort',
'phone' => 'Telefon',
'mobile' => 'Mobil',
'email' => 'E-Mail-Adresse',
];
public const DEFAULT_CONTACT_FIELDS = ['job_title', 'phone', 'email'];
public function __construct(private readonly QmTree $tree, private readonly Settings $settings, private readonly ProfileFields $profileFields) {}
/**
* @param array<int, int> $counts Ordner => Anzahl Einträge
* @return array<string, mixed>
*/
public function tile(int $id, array $counts = []): array
{
$folder = $this->tree->folder($id);
$children = count($this->tree->childIds($id));
return [
'id' => $id,
'name' => $folder['name'],
'color' => $folder['color'],
'icon' => $folder['icon'],
'folders' => $children,
'entries' => (int) ($counts[$id] ?? 0),
'url' => route('qm.folder', $id),
];
}
/**
* @return array<string, mixed>
*/
public function entry(QmEntry $entry, bool $withFolder = false): array
{
$reading = $entry->relationLoaded('readingFile') ? $entry->readingFile : null;
$editable = $entry->relationLoaded('editableFile') ? $entry->editableFile : null;
$main = $reading ?? $editable;
$open = match ($entry->type) {
QmEntry::LINK => ['url' => $entry->url, 'kind' => 'link'],
QmEntry::FORM => ['url' => $entry->form_id ? $this->formUrl($entry->form_id) : null, 'kind' => 'form'],
default => $main
? ($main->isViewable() ? ['url' => route('qm.view', $entry), 'kind' => 'view'] : ['url' => $main->url(), 'kind' => 'download'])
: ['url' => null, 'kind' => 'none'],
};
return [
'id' => $entry->id,
'type' => $entry->type,
'title' => $entry->title,
'description' => $entry->description,
'version' => $entry->version,
'valid_from' => $entry->valid_from?->toDateString(),
'size' => $main?->size,
'extension' => $main?->extension(),
'open_url' => $open['url'],
'open_kind' => $open['kind'],
'download_url' => $main?->url(),
'editable' => $editable ? ['name' => $editable->name, 'extension' => $editable->extension(), 'url' => $editable->url(), 'size' => $editable->size] : null,
'searchable' => $main ? in_array($main->text_status, ['ok', 'ocr'], true) : null,
'text_status' => $main?->text_status,
'url' => $entry->url,
'form_id' => $entry->form_id,
'folder' => $withFolder ? $this->folderLabel($entry->folder_id) : null,
];
}
/**
* @return array{id: int, path: string, color: string}
*/
public function folderLabel(int $id): array
{
return [
'id' => $id,
'path' => implode(' › ', array_column($this->tree->path($id), 'name')),
'color' => $this->tree->folder($id)['color'] ?? Colors::DEFAULT,
'url' => route('qm.folder', $id),
];
}
/**
* Ansprechpartner mit den im Admin gewählten Profilfeldern.
*
* @param iterable<User> $people
* @return list<array<string, mixed>>
*/
public function contacts(iterable $people, ?User $viewer): array
{
$fields = (array) $this->settings->get(self::CONTACT_FIELDS, self::DEFAULT_CONTACT_FIELDS);
$result = [];
foreach ($people as $person) {
if (! $person->is_active) {
continue;
}
$values = [];
$custom = collect($this->profileFields->visibleValues($person, $viewer))->keyBy('key');
foreach ($fields as $field) {
if (isset(self::CORE_FIELDS[$field])) {
$value = $person->{$field};
if (filled($value)) {
$values[] = ['key' => $field, 'label' => self::CORE_FIELDS[$field], 'value' => $value, 'type' => in_array($field, ['phone', 'mobile'], true) ? 'phone' : ($field === 'email' ? 'email' : 'text')];
}
} elseif (str_starts_with($field, 'custom.') && ($item = $custom->get(substr($field, 7)))) {
$values[] = ['key' => $field, 'label' => $item['label'], 'value' => $item['value'], 'type' => $item['type'] ?? 'text'];
}
}
$result[] = [
'id' => $person->id,
'name' => $person->name,
'initials' => $person->initials,
'avatar_url' => $person->avatarUrl(160),
'fields' => $values,
];
}
return $result;
}
/**
* @return array<string, string> auswählbare Felder für die Einstellungen
*/
public function contactFieldOptions(): array
{
return self::CORE_FIELDS + collect($this->profileFields->options())->mapWithKeys(fn ($label, $key) => ['custom.'.$key => $label.' (Profilfeld)'])->all();
}
private function formUrl(int $id): ?string
{
$class = 'Inhaus\\Plugins\\Forms\\Models\\Form';
return class_exists($class) ? $class::query()->find($id)?->url() : null;
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace Inhaus\Plugins\Qm;
use App\Models\User;
use App\Support\Settings;
/**
* Wer das QM-Modul sehen und pflegen darf.
*
* - Sehen: alle angemeldeten Personen – außer Mitgliedern ausgeschlossener Rollen
* (z. B. Klient*innen). Ausschluss geht vor; wer QM pflegen darf, sieht es immer.
* - Pflegen: Recht „qm.manage“ (ohne Vergabe nur die Administration).
*/
class QmAccess
{
public const EXCLUDED_ROLES = 'qm.excluded_roles';
public function __construct(private readonly Settings $settings) {}
public function allows(?User $user): bool
{
if (! $user) {
return false;
}
if ($this->canManage($user)) {
return true;
}
$excluded = array_map('intval', (array) $this->settings->get(self::EXCLUDED_ROLES, []));
return $excluded === [] || ! $user->roles()->whereIn('roles.id', $excluded)->exists();
}
public function canManage(?User $user): bool
{
return (bool) $user?->can('qm.manage');
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Inhaus\Plugins\Qm;
use App\Models\User;
use App\Plugins\Plugin;
use App\Support\Abilities;
use App\Support\Navigation;
use Illuminate\Support\Facades\Schedule;
use Inhaus\Plugins\Qm\Models\QmCategory;
use Inhaus\Plugins\Qm\Text\Ocr;
use Inhaus\Plugins\Qm\Text\TextExtractor;
class QmPlugin extends Plugin
{
public function register(): void
{
foreach ([QmTree::class, QmAccess::class, Presenter::class, Search::class, Library::class, Indexer::class, TextExtractor::class, Ocr::class] as $class) {
$this->app->singleton($class);
}
$this->app->make(Navigation::class)->add('qm', 'Qualitätsmanagement', '/qm', active: 'qm.*', sort: 55,
visible: fn (User $user) => $this->app->make(QmAccess::class)->allows($user));
$abilities = $this->app->make(Abilities::class);
$abilities->define('qm.manage', 'Qualitätsmanagement pflegen (Ordner, Dokumente, Einstellungen)', 'Qualitätsmanagement');
$abilities->resourceType('qm_category', 'QM-Kategorie', fn () => QmCategory::query()->orderBy('sort')->pluck('name', 'id')->all());
}
public function boot(): void
{
// Eingescannte PDFs per Texterkennung durchsuchbar machen (nur wenn eingerichtet).
Schedule::call(fn () => $this->app->make(Indexer::class)->processOcr())
->everyTenMinutes()->name('qm-ocr')->withoutOverlapping(30);
}
}

View file

@ -0,0 +1,206 @@
<?php
namespace Inhaus\Plugins\Qm;
use App\Models\User;
use App\Support\Icons;
use App\Support\Permissions\Audiences;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
/**
* Ordnerstruktur des QM-Moduls, zwischengespeichert: Kategorien, Ordner, geerbte
* Farben und Sichtbarkeit (je Kategorie, vorbereitet über Zielgruppen).
*/
class QmTree
{
private const CACHE_KEY = 'qm.tree';
/** @var array<string, mixed>|null */
private ?array $data = null;
public static function flush(): void
{
Cache::forget(self::CACHE_KEY);
app(self::class)->data = null;
}
/**
* @return array{id: int, parent_id: ?int, category_id: ?int, name: string, color: string, own_color: ?string, icon: array{name?: string, url?: string, mono?: bool}, sort: int}|null
*/
public function folder(int $id): ?array
{
return $this->data()['folders'][$id] ?? null;
}
/**
* @return list<int>
*/
public function childIds(?int $id): array
{
return $this->data()['children'][$id ?? 0] ?? [];
}
/**
* @return list<array<string, mixed>> Weg von oben bis einschließlich des Ordners
*/
public function path(int $id): array
{
$path = [];
for ($folder = $this->folder($id); $folder && count($path) < 50; $folder = $folder['parent_id'] ? $this->folder($folder['parent_id']) : null) {
array_unshift($path, $folder);
}
return $path;
}
/**
* @param list<int> $ids
* @return list<int>
*/
public function descendantIds(array $ids): array
{
$result = [];
foreach ($ids as $id) {
foreach ($this->childIds($id) as $child) {
$result[] = $child;
array_push($result, ...$this->descendantIds([$child]));
}
}
return $result;
}
/**
* Kategorie eines Ordners (die des obersten Ordners im Pfad).
*/
public function categoryId(int $id): ?int
{
return $this->path($id)[0]['category_id'] ?? null;
}
public function isVisible(int $id, ?User $user): bool
{
if (! $this->folder($id)) {
return false;
}
$category = $this->categoryId($id);
return $category === null || $this->categoryVisible($category, $user);
}
public function categoryVisible(int $category, ?User $user): bool
{
return Audiences::matches($this->data()['category_audiences'][$category] ?? null, $user);
}
/**
* @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)));
}
/**
* Kategorien mit ihren obersten Ordnern – für die Startseite.
*
* @return list<array{id: int|null, name: string, folders: list<int>}>
*/
public function categories(?User $user): array
{
$groups = [];
foreach ($this->data()['categories'] as $category) {
if (! $this->categoryVisible($category['id'], $user)) {
continue;
}
$folders = array_values(array_filter($this->childIds(null), fn (int $id) => $this->folder($id)['category_id'] === $category['id']));
if ($folders !== []) {
$groups[] = ['id' => $category['id'], 'name' => $category['name'], 'folders' => $folders];
}
}
// Oberste Ordner ohne (gültige) Kategorie
$known = array_column($this->data()['categories'], 'id');
$rest = array_values(array_filter($this->childIds(null), fn (int $id) => ! in_array($this->folder($id)['category_id'], $known, true)));
if ($rest !== []) {
$groups[] = ['id' => null, 'name' => $groups === [] ? 'Ordner' : 'Weitere', 'folders' => $rest];
}
return $groups;
}
/**
* Alle Ordner mit Einrückung – für Auswahllisten.
*
* @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->folder($id)['name'];
$options += $this->options($id, $depth + 1);
}
return $options;
}
/**
* @return array<string, mixed>
*/
private function data(): array
{
return $this->data ??= Cache::rememberForever(self::CACHE_KEY, function () {
$categories = DB::table('qm_categories')->orderBy('sort')->orderBy('name')->get(['id', 'name'])
->map(fn ($c) => ['id' => (int) $c->id, 'name' => $c->name])->all();
$rows = DB::table('qm_folders')->orderBy('sort')->orderBy('name')->get(['id', 'parent_id', 'category_id', 'name', 'color', 'icon', 'icon_path', 'icon_mono', 'sort']);
$folders = [];
$children = [];
foreach ($rows as $row) {
$folders[(int) $row->id] = [
'id' => (int) $row->id,
'parent_id' => $row->parent_id ? (int) $row->parent_id : null,
'category_id' => $row->category_id ? (int) $row->category_id : null,
'name' => $row->name,
'own_color' => Colors::has($row->color) ? $row->color : null,
'color' => Colors::DEFAULT,
'own_icon' => $row->icon_path
? ['url' => Storage::disk('uploads')->url($row->icon_path), 'mono' => (bool) $row->icon_mono]
: (Icons::has($row->icon) ? ['name' => $row->icon] : null),
'icon' => ['name' => 'folder'],
'sort' => (int) $row->sort,
];
$children[(int) ($row->parent_id ?? 0)][] = (int) $row->id;
}
// Farbe und Symbol vererben: von oben nach unten auflösen.
$resolve = function (int $parent, string $color, array $icon) use (&$resolve, &$folders, $children) {
foreach ($children[$parent] ?? [] as $id) {
$folders[$id]['color'] = $folders[$id]['own_color'] ?? $color;
$folders[$id]['icon'] = $folders[$id]['own_icon'] ?? $icon;
$resolve($id, $folders[$id]['color'], $folders[$id]['icon']);
}
};
$resolve(0, Colors::DEFAULT, ['name' => 'folder']);
return [
'categories' => $categories,
'folders' => $folders,
'children' => $children,
'category_audiences' => Audiences::allOfType('qm_category'),
];
});
}
}

View file

@ -0,0 +1,144 @@
<?php
namespace Inhaus\Plugins\Qm;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Inhaus\Plugins\Qm\Models\QmEntry;
/**
* Suche nur im QM-Modul: Titel, Beschreibung, Dateiname und Inhalt der aktuellen
* Fassungen (Volltextindex, sonst Textsuche). Treffer mit Textausschnitt.
*/
class Search
{
public const LIMIT = 50;
public function __construct(private readonly QmTree $tree) {}
/**
* @return Collection<int, array{entry: QmEntry, snippet: ?string, in_content: bool}>
*/
public function run(string $query, ?User $user): Collection
{
$terms = $this->terms($query);
if ($terms === []) {
return collect();
}
$folders = $this->tree->visibleIds($user) ?: [0];
$like = fn (string $term) => '%'.str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $term).'%';
// 1) Metadaten: alle Begriffe in Titel, Beschreibung, Version oder Dateiname
$byMeta = QmEntry::query()->whereIn('folder_id', $folders)
->where(function (Builder $q) use ($terms, $like) {
foreach ($terms as $term) {
$q->where(fn (Builder $w) => $w->where('title', 'like', $like($term))
->orWhere('description', 'like', $like($term))
->orWhere('version', 'like', $like($term))
->orWhereHas('files', fn (Builder $f) => $f->whereNull('archived_at')->where('name', 'like', $like($term))));
}
})
->limit(self::LIMIT)->pluck('id')->all();
// 2) Inhalt: Volltextindex (schnell, mit Gewichtung) – Rückfall auf Textsuche
$contentHits = $this->contentMatches($terms, $folders, $like);
$ids = array_values(array_unique([...$byMeta, ...array_keys($contentHits)]));
$entries = QmEntry::query()->whereIn('id', $ids ?: [0])->with(['readingFile', 'editableFile'])->get()->keyBy('id');
return collect($ids)
->filter(fn (int $id) => $entries->has($id))
->map(fn (int $id) => [
'entry' => $entries[$id],
'snippet' => isset($contentHits[$id]) ? $this->snippet($contentHits[$id], $terms) : null,
'in_content' => isset($contentHits[$id]) && ! in_array($id, $byMeta, true),
])
->take(self::LIMIT)
->values();
}
/**
* @param list<string> $terms
* @param list<int> $folders
* @return array<int, string> Eintrag => Text
*/
private function contentMatches(array $terms, array $folders, \Closure $like): array
{
$base = fn () => DB::table('qm_files')->join('qm_entries', 'qm_entries.id', '=', 'qm_files.entry_id')
->whereIn('qm_entries.folder_id', $folders)->whereNull('qm_files.archived_at')->whereNotNull('qm_files.text');
$rows = collect();
if (in_array(DB::getDriverName(), ['mysql', 'mariadb'], true) && collect($terms)->every(fn ($t) => mb_strlen($t) >= 3)) {
$boolean = implode(' ', array_map(fn ($t) => '+'.preg_replace('/[^\p{L}\p{N}]+/u', '', $t).'*', $terms));
$rows = $base()->whereRaw('MATCH(qm_files.text) AGAINST (? IN BOOLEAN MODE)', [$boolean])
->orderByRaw('MATCH(qm_files.text) AGAINST (? IN BOOLEAN MODE) DESC', [$boolean])
->limit(self::LIMIT)->get(['qm_files.entry_id', 'qm_files.kind', 'qm_files.text']);
}
// Kurze Begriffe, frisch gespeicherte Zeilen oder andere Datenbanken
if ($rows->isEmpty()) {
$query = $base();
foreach ($terms as $term) {
$query->where('qm_files.text', 'like', $like($term));
}
$rows = $query->limit(self::LIMIT)->get(['qm_files.entry_id', 'qm_files.kind', 'qm_files.text']);
}
// Je Eintrag ein Text – die Lesefassung vor der Vorlage.
$texts = [];
foreach ($rows as $row) {
if (! isset($texts[(int) $row->entry_id]) || $row->kind === 'reading') {
$texts[(int) $row->entry_id] = (string) $row->text;
}
}
return $texts;
}
/**
* @return list<string>
*/
private function terms(string $query): array
{
$words = preg_split('/\s+/u', mb_strtolower(trim($query)), -1, PREG_SPLIT_NO_EMPTY) ?: [];
return array_values(array_unique(array_filter(array_slice($words, 0, 8), fn ($w) => mb_strlen($w) >= 2)));
}
/**
* Ausschnitt rund um den ersten Treffer, Begriffe hervorgehoben (HTML, escaped).
*
* @param list<string> $terms
*/
private function snippet(string $text, array $terms): string
{
$lower = mb_strtolower($text);
$position = null;
foreach ($terms as $term) {
$found = mb_strpos($lower, $term);
if ($found !== false && ($position === null || $found < $position)) {
$position = $found;
}
}
$start = max(0, ($position ?? 0) - 80);
$excerpt = str_replace("\n", ' ', mb_substr($text, $start, 240));
$html = ($start > 0 ? '… ' : '').e($excerpt).(mb_strlen($text) > $start + 240 ? ' …' : '');
foreach ($terms as $term) {
$html = preg_replace('/('.preg_quote(e($term), '/').')/iu', '<mark>$1</mark>', $html) ?? $html;
}
return $html;
}
}

View file

@ -0,0 +1,163 @@
<?php
namespace Inhaus\Plugins\Qm\Text;
use App\Support\Settings;
use Imagick;
use Throwable;
/**
* Texterkennung (OCR) für eingescannte PDFs – optional, wenn der Server sie kann:
* Tesseract (Programm „tesseract“ mit deutschen Sprachdaten) und ein Umwandler für
* PDF-Seiten in Bilder (Programm „pdftoppm“ aus poppler-utils oder PHP-Imagick mit
* Ghostscript). Auf Shared Hosting meist nicht vorhanden – dann bleiben solche
* Dateien in der Suche nur über ihren Titel auffindbar.
*
* Einrichtung (Debian/Ubuntu): apt install tesseract-ocr tesseract-ocr-deu poppler-utils
*/
class Ocr
{
public const SETTING_ENABLED = 'qm.ocr.enabled';
public const SETTING_BINARY = 'qm.ocr.tesseract';
public const MAX_PAGES = 40;
public function __construct(private readonly Settings $settings) {}
public function enabled(): bool
{
return (bool) $this->settings->get(self::SETTING_ENABLED, false);
}
/**
* Was auf diesem Server vorhanden ist.
*
* @return array{exec: bool, // Programme dürfen aufgerufen werden (proc_open)
* tesseract: ?string, languages: list<string>, rasterizer: ?string}
*/
public function status(): array
{
$exec = function_exists('proc_open') && ! in_array('proc_open', array_map('trim', explode(',', (string) ini_get('disable_functions'))), true);
$tesseract = null;
$languages = [];
if ($exec) {
$binary = $this->binary();
$version = $this->run([$binary, '--version']);
if ($version !== null && str_contains(strtolower($version), 'tesseract')) {
$tesseract = trim(strtok($version, "\n"));
$languages = array_values(array_filter(array_map('trim', array_slice(explode("\n", (string) $this->run([$binary, '--list-langs'])), 1))));
}
}
return ['exec' => $exec, 'tesseract' => $tesseract, 'languages' => $languages, 'rasterizer' => $this->rasterizer($exec)];
}
public function available(): bool
{
$status = $this->status();
return $status['tesseract'] !== null && $status['rasterizer'] !== null;
}
/**
* Text einer PDF-Datei per Texterkennung.
*/
public function recognize(string $pdf): string
{
$dir = sys_get_temp_dir().'/inhaus-ocr-'.bin2hex(random_bytes(6));
@mkdir($dir, 0700, true);
try {
$images = $this->rasterize($pdf, $dir);
$languages = in_array('deu', $this->status()['languages'], true) ? 'deu+eng' : 'eng';
$text = '';
foreach ($images as $image) {
$text .= $this->run([$this->binary(), $image, 'stdout', '-l', $languages, '--psm', '1'])."\n";
}
return TextExtractor::normalize($text);
} finally {
array_map('unlink', glob($dir.'/*') ?: []);
@rmdir($dir);
}
}
private function binary(): string
{
$binary = trim((string) $this->settings->get(self::SETTING_BINARY, '')) ?: 'tesseract';
// Nur ein Programmname oder ein absoluter Pfad – keine Parameter.
return preg_match('#^(/[\w./-]+|[\w.-]+)$#', $binary) ? $binary : 'tesseract';
}
private function rasterizer(bool $exec): ?string
{
if ($exec && $this->run(['pdftoppm', '-v']) !== null) {
return 'pdftoppm';
}
try {
if (class_exists(Imagick::class) && in_array('PDF', Imagick::queryFormats('PDF'), true)) {
return 'imagick';
}
} catch (Throwable) {
// Imagick ohne PDF-Unterstützung
}
return null;
}
/**
* @return list<string> Bilddateien der Seiten
*/
private function rasterize(string $pdf, string $dir): array
{
if ($this->rasterizer(true) === 'pdftoppm') {
$this->run(['pdftoppm', '-r', '300', '-gray', '-png', '-l', (string) self::MAX_PAGES, $pdf, $dir.'/seite']);
} else {
$imagick = new Imagick;
$imagick->setResolution(300, 300);
$imagick->readImage($pdf.'[0-'.(self::MAX_PAGES - 1).']');
foreach ($imagick as $index => $page) {
$page->setImageFormat('png');
$page->writeImage(sprintf('%s/seite-%03d.png', $dir, $index + 1));
}
$imagick->clear();
}
$images = glob($dir.'/seite*.png') ?: [];
natsort($images);
return array_values($images);
}
/**
* Programm ohne Shell aufrufen; null, wenn es nicht läuft.
*
* @param list<string> $command
*/
protected function run(array $command): ?string
{
if (! function_exists('proc_open')) {
return null;
}
$process = @proc_open($command, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
if (! is_resource($process)) {
return null;
}
$output = stream_get_contents($pipes[1]).stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
return proc_close($process) === 0 ? (string) $output : null;
}
}

View file

@ -0,0 +1,120 @@
<?php
namespace Inhaus\Plugins\Qm\Text;
use Smalot\PdfParser\Parser;
use Throwable;
use ZipArchive;
/**
* Text aus Dokumenten für die Volltextsuche – in reinem PHP, läuft also auch auf
* Shared Hosting. Eingescannte PDFs ohne Textebene liefern nichts; die übernimmt
* (falls eingerichtet) die Texterkennung (Ocr).
*/
class TextExtractor
{
/** Mehr Text braucht die Suche nicht. */
public const MAX_CHARS = 2_000_000;
/**
* @return array{text: ?string, status: string} status: ok | empty | unsupported | failed
*/
public function extract(string $path, string $extension): array
{
try {
$text = match (strtolower($extension)) {
'pdf' => $this->pdf($path),
'docx' => $this->xmlInZip($path, ['word/document.xml', 'word/header1.xml', 'word/footer1.xml']),
'xlsx' => $this->xmlInZip($path, ['xl/sharedStrings.xml']),
'pptx' => $this->xmlInZip($path, $this->zipEntries($path, '#^ppt/slides/slide\d+\.xml$#')),
'odt', 'ods', 'odp' => $this->xmlInZip($path, ['content.xml']),
'txt', 'csv' => (string) file_get_contents($path, length: self::MAX_CHARS),
default => null,
};
} catch (Throwable $e) {
logger()->warning("QM: Text aus {$path} nicht lesbar: ".$e->getMessage());
return ['text' => null, 'status' => 'failed'];
}
if ($text === null) {
return ['text' => null, 'status' => 'unsupported'];
}
$text = self::normalize($text);
return ['text' => $text === '' ? null : $text, 'status' => $text === '' ? 'empty' : 'ok'];
}
public static function normalize(string $text): string
{
$text = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
$text = preg_replace('/[^\P{C}\n\t]+/u', ' ', $text) ?? '';
$text = preg_replace('/[ \t\x{00A0}]+/u', ' ', $text) ?? '';
$text = preg_replace('/\s*\n\s*/', "\n", $text) ?? '';
return mb_substr(trim($text), 0, self::MAX_CHARS);
}
private function pdf(string $path): string
{
$parser = new Parser;
return $parser->parseFile($path)->getText();
}
/**
* @param list<string> $entries
*/
private function xmlInZip(string $path, array $entries): string
{
$zip = new ZipArchive;
if ($zip->open($path) !== true) {
throw new \RuntimeException('Keine gültige Office-Datei.');
}
$text = '';
foreach ($entries as $entry) {
$xml = $zip->getFromName($entry);
if ($xml !== false) {
// Absätze und Zellen als Zeilen, dann Tags entfernen.
$xml = preg_replace('#</(w:p|a:p|text:p|text:h|si|table:table-cell)>#', "\n", $xml);
$text .= html_entity_decode(strip_tags((string) $xml), ENT_QUOTES | ENT_XML1, 'UTF-8')."\n";
}
}
$zip->close();
return $text;
}
/**
* @return list<string>
*/
private function zipEntries(string $path, string $pattern): array
{
$zip = new ZipArchive;
if ($zip->open($path) !== true) {
return [];
}
$names = [];
for ($i = 0; $i < $zip->numFiles; $i++) {
$name = (string) $zip->getNameIndex($i);
if (preg_match($pattern, $name)) {
$names[] = $name;
}
}
$zip->close();
natsort($names);
return array_values($names);
}
}