Loheide-eu-mitarbeiterplatt.../plugins-core/qm/src/Search.php
Friederich Loheide b3a057e27c
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
Neues Modul: Qualitätsmanagement
- 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>
2026-09-26 15:50:23 +00:00

144 lines
5.3 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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