…, 'url' => …, 'text' => Klartext, 'meta' => ?string] */ class Knowledge { /** Höchstens so viel Text je Treffer – ausgewählt wird später ohnehin nur ein Ausschnitt */ public const MAX_TEXT = 30000; /** @var array */ private array $sources = []; /** * Die Quelle bekommt Person, Suchbegriffe (klein geschrieben; ein Treffer enthält * mindestens einen) und Höchstzahl. * * @param callable(User, list, int): list> $search */ public function add(string $key, string $label, callable $search): void { $this->sources[$key] = compact('label', 'search'); } public function remove(string $key): void { unset($this->sources[$key]); } /** * @return array Schlüssel => Bezeichnung */ public function labels(): array { return array_map(fn (array $source) => $source['label'], $this->sources); } /** * @param list $terms * @return list */ public function gather(User $user, array $terms, int $perSource = 8): array { if ($terms === []) { return []; } $documents = []; foreach ($this->sources as $key => $source) { if (! app(PluginAccess::class)->allows($key, $user)) { continue; } try { // Einmal mit allen Begriffen, dazu je Begriff ein paar Treffer – sonst verdrängt ein // häufiges Wort („Werkstatt“) die wenigen Einträge mit dem entscheidenden („Sammelplatz“) $hits = array_slice(($source['search'])($user, $terms, $perSource), 0, $perSource); if (count($terms) > 1) { foreach ($terms as $term) { $hits = [...$hits, ...array_slice(($source['search'])($user, [$term], 3), 0, 3)]; } } $seen = []; foreach ($hits as $hit) { if (isset($seen[$hit['url'].'|'.$hit['title']])) { continue; } $seen[$hit['url'].'|'.$hit['title']] = true; $documents[] = [ 'source' => $key, 'label' => $source['label'], 'title' => (string) $hit['title'], 'url' => (string) $hit['url'], 'text' => mb_substr((string) $hit['text'], 0, self::MAX_TEXT), 'meta' => $hit['meta'] ?? null, ]; } } catch (Throwable $e) { // Eine fehlerhafte Quelle darf die Antwort nicht verhindern. Log::error("Wissensquelle {$key} fehlgeschlagen: ".$e->getMessage(), ['exception' => $e]); } } return $documents; } /** * Mindestens einer der Begriffe in mindestens einer der Spalten. * * @template T of Builder|QueryBuilder * * @param T $query * @param list $columns * @param list $terms * @return T */ public static function whereAny(Builder|QueryBuilder $query, array $columns, array $terms): Builder|QueryBuilder { return $query->where(function ($q) use ($columns, $terms) { foreach ($terms as $term) { // Kurze Begriffe („it“, „qm“) nur als ganzes Wort – sonst fände „it“ jedes „mit“ if (self::isShort($term)) { $pattern = '(^|[^[:alnum:]])'.preg_quote($term).'([^[:alnum:]]|$)'; foreach ($columns as $column) { $q->orWhereRaw(self::lowered($column).' REGEXP ?', [$pattern]); } continue; } $like = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $term).'%'; foreach ($columns as $column) { $q->orWhereRaw(self::lowered($column).' LIKE ?', [$like]); } } }); } /** * Spalte klein geschrieben als Text – JSON-Spalten (z. B. Inhalte aus dem Baukasten) haben eine * binäre Sortierung, dort wäre LIKE sonst groß-/kleinschreibungsabhängig. */ private static function lowered(string $column): string { return 'LOWER(CAST('.DB::getQueryGrammar()->wrap($column).' AS CHAR))'; } public static function isShort(string $term): bool { return mb_strlen($term) <= 3; } /** Wie oft kommt der Begriff vor? Kurze Begriffe nur als ganzes Wort. */ public static function occurrences(string $haystack, string $term): int { return self::isShort($term) ? (int) preg_match_all('/(?]*>#i', "\n", (string) $html) ?? ''; $text = html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5); return trim(preg_replace(["/[ \t]+/u", "/\n\s*\n+/u"], [' ', "\n"], $text) ?? ''); } }