3 namespace BookStack\Search;
5 use BookStack\Activity\Models\Tag;
6 use BookStack\Entities\EntityProvider;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Entities\Models\Page;
9 use BookStack\Util\HtmlDocument;
11 use Illuminate\Database\Eloquent\Builder;
12 use Illuminate\Support\Collection;
17 * A list of delimiter characters used to break-up parsed content into terms for indexing.
19 public static string $delimiters = " \n\t.,!?:;()[]{}<>`'\"";
21 public function __construct(
22 protected EntityProvider $entityProvider
27 * Index the given entity.
29 public function indexEntity(Entity $entity): void
31 $this->deleteEntityTerms($entity);
32 $terms = $this->entityToTermDataArray($entity);
33 SearchTerm::query()->insert($terms);
37 * Index multiple Entities at once.
39 * @param Entity[] $entities
41 public function indexEntities(array $entities): void
44 foreach ($entities as $entity) {
45 $entityTerms = $this->entityToTermDataArray($entity);
46 array_push($terms, ...$entityTerms);
49 $chunkedTerms = array_chunk($terms, 500);
50 foreach ($chunkedTerms as $termChunk) {
51 SearchTerm::query()->insert($termChunk);
56 * Delete and re-index the terms for all entities in the system.
57 * Can take a callback which is used for reporting progress.
58 * Callback receives three arguments:
59 * - An instance of the model being processed
60 * - The number that have been processed so far.
61 * - The total number of that model to be processed.
63 * @param callable(Entity, int, int):void|null $progressCallback
65 public function indexAllEntities(?callable $progressCallback = null): void
67 SearchTerm::query()->truncate();
69 foreach ($this->entityProvider->all() as $entityModel) {
70 $indexContentField = $entityModel instanceof Page ? 'html' : 'description';
71 $selectFields = ['id', 'name', $indexContentField];
72 /** @var Builder<Entity> $query */
73 $query = $entityModel->newQuery();
74 $total = $query->withTrashed()->count();
78 $chunkCallback = function (Collection $entities) use ($progressCallback, &$processed, $total, $chunkSize, $entityModel) {
79 $this->indexEntities($entities->all());
80 $processed = min($processed + $chunkSize, $total);
82 if (is_callable($progressCallback)) {
83 $progressCallback($entityModel, $processed, $total);
87 $entityModel->newQuery()
88 ->select($selectFields)
89 ->with(['tags:id,name,value,entity_id,entity_type'])
90 ->chunk($chunkSize, $chunkCallback);
95 * Delete related Entity search terms.
97 public function deleteEntityTerms(Entity $entity): void
99 $entity->searchTerms()->delete();
103 * Create a scored term array from the given text, where the keys are the terms
104 * and the values are their scores.
106 * @returns array<string, int>
108 protected function generateTermScoreMapFromText(string $text, float $scoreAdjustment = 1): array
110 $termMap = $this->textToTermCountMap($text);
112 foreach ($termMap as $term => $count) {
113 $termMap[$term] = floor($count * $scoreAdjustment);
120 * Create a scored term array from the given HTML, where the keys are the terms
121 * and the values are their scores.
123 * @returns array<string, int>
125 protected function generateTermScoreMapFromHtml(string $html): array
132 $elementScoreAdjustmentMap = [
141 $html = str_ireplace(['<br>', '<br />', '<br/>'], "\n", $html);
142 $doc = new HtmlDocument($html);
144 /** @var DOMNode $child */
145 foreach ($doc->getBodyChildren() as $child) {
146 $nodeName = $child->nodeName;
147 $termCounts = $this->textToTermCountMap(trim($child->textContent));
148 foreach ($termCounts as $term => $count) {
149 $scoreChange = $count * ($elementScoreAdjustmentMap[$nodeName] ?? 1);
150 $scoresByTerm[$term] = ($scoresByTerm[$term] ?? 0) + $scoreChange;
154 return $scoresByTerm;
158 * Create a scored term map from the given set of entity tags.
162 * @returns array<string, int>
164 protected function generateTermScoreMapFromTags(array $tags): array
169 foreach ($tags as $tag) {
170 $names[] = $tag->name;
171 $values[] = $tag->value;
174 $nameMap = $this->generateTermScoreMapFromText(implode(' ', $names), 3);
175 $valueMap = $this->generateTermScoreMapFromText(implode(' ', $values), 5);
177 return $this->mergeTermScoreMaps($nameMap, $valueMap);
181 * For the given text, return an array where the keys are the unique term words
182 * and the values are the frequency of that term.
184 * @returns array<string, int>
186 protected function textToTermCountMap(string $text): array
188 $tokenMap = []; // {TextToken => OccurrenceCount}
189 $splitChars = static::$delimiters;
190 $token = strtok($text, $splitChars);
192 while ($token !== false) {
193 if (!isset($tokenMap[$token])) {
194 $tokenMap[$token] = 0;
197 $token = strtok($splitChars);
204 * For the given entity, Generate an array of term data details.
205 * Is the raw term data, not instances of SearchTerm models.
207 * @returns array{term: string, score: float, entity_id: int, entity_type: string}[]
209 protected function entityToTermDataArray(Entity $entity): array
211 $nameTermsMap = $this->generateTermScoreMapFromText($entity->name, 40 * $entity->searchFactor);
212 $tagTermsMap = $this->generateTermScoreMapFromTags($entity->tags->all());
214 if ($entity instanceof Page) {
215 $bodyTermsMap = $this->generateTermScoreMapFromHtml($entity->html);
217 $bodyTermsMap = $this->generateTermScoreMapFromText($entity->getAttribute('description') ?? '', $entity->searchFactor);
220 $mergedScoreMap = $this->mergeTermScoreMaps($nameTermsMap, $bodyTermsMap, $tagTermsMap);
223 $entityId = $entity->id;
224 $entityType = $entity->getMorphClass();
225 foreach ($mergedScoreMap as $term => $score) {
229 'entity_type' => $entityType,
230 'entity_id' => $entityId,
238 * For the given term data arrays, Merge their contents by term
239 * while combining any scores.
241 * @param array<string, int>[] ...$scoreMaps
243 * @returns array<string, int>
245 protected function mergeTermScoreMaps(...$scoreMaps): array
249 foreach ($scoreMaps as $scoreMap) {
250 foreach ($scoreMap as $term => $score) {
251 $mergedMap[$term] = ($mergedMap[$term] ?? 0) + $score;