…, '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 { foreach (array_slice(($source['search'])($user, $terms, $perSource), 0, $perSource) as $hit) { $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) { $like = '%'.str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $term).'%'; foreach ($columns as $column) { $q->orWhere($column, 'like', $like); } } }); } /** HTML in lesbaren Klartext (Absätze bleiben als Zeilenumbrüche erhalten) */ public static function plain(?string $html): string { $text = preg_replace('#<(br|/p|/li|/h[1-6]|/tr|/div)\b[^>]*>#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) ?? ''); } }