]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/SearchIndex.php
feat(PageContent): set unique ids on nested headers
[bookstack] / app / Entities / Tools / SearchIndex.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use BookStack\Actions\Tag;
6 use BookStack\Entities\EntityProvider;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Entities\Models\Page;
9 use BookStack\Entities\Models\SearchTerm;
10 use DOMDocument;
11 use DOMNode;
12 use Illuminate\Support\Collection;
13
14 class SearchIndex
15 {
16     /**
17      * A list of delimiter characters used to break-up parsed content into terms for indexing.
18      *
19      * @var string
20      */
21     public static $delimiters = " \n\t.,!?:;()[]{}<>`'\"";
22
23     /**
24      * @var EntityProvider
25      */
26     protected $entityProvider;
27
28     public function __construct(EntityProvider $entityProvider)
29     {
30         $this->entityProvider = $entityProvider;
31     }
32
33     /**
34      * Index the given entity.
35      */
36     public function indexEntity(Entity $entity)
37     {
38         $this->deleteEntityTerms($entity);
39         $terms = $this->entityToTermDataArray($entity);
40         SearchTerm::query()->insert($terms);
41     }
42
43     /**
44      * Index multiple Entities at once.
45      *
46      * @param Entity[] $entities
47      */
48     public function indexEntities(array $entities)
49     {
50         $terms = [];
51         foreach ($entities as $entity) {
52             $entityTerms = $this->entityToTermDataArray($entity);
53             array_push($terms, ...$entityTerms);
54         }
55
56         $chunkedTerms = array_chunk($terms, 500);
57         foreach ($chunkedTerms as $termChunk) {
58             SearchTerm::query()->insert($termChunk);
59         }
60     }
61
62     /**
63      * Delete and re-index the terms for all entities in the system.
64      * Can take a callback which is used for reporting progress.
65      * Callback receives three arguments:
66      * - An instance of the model being processed
67      * - The number that have been processed so far.
68      * - The total number of that model to be processed.
69      *
70      * @param callable(Entity, int, int)|null $progressCallback
71      */
72     public function indexAllEntities(?callable $progressCallback = null)
73     {
74         SearchTerm::query()->truncate();
75
76         foreach ($this->entityProvider->all() as $entityModel) {
77             $indexContentField = $entityModel instanceof Page ? 'html' : 'description';
78             $selectFields = ['id', 'name', $indexContentField];
79             $total = $entityModel->newQuery()->withTrashed()->count();
80             $chunkSize = 250;
81             $processed = 0;
82
83             $chunkCallback = function (Collection $entities) use ($progressCallback, &$processed, $total, $chunkSize, $entityModel) {
84                 $this->indexEntities($entities->all());
85                 $processed = min($processed + $chunkSize, $total);
86
87                 if (is_callable($progressCallback)) {
88                     $progressCallback($entityModel, $processed, $total);
89                 }
90             };
91
92             $entityModel->newQuery()
93                 ->select($selectFields)
94                 ->with(['tags:id,name,value,entity_id,entity_type'])
95                 ->chunk($chunkSize, $chunkCallback);
96         }
97     }
98
99     /**
100      * Delete related Entity search terms.
101      */
102     public function deleteEntityTerms(Entity $entity)
103     {
104         $entity->searchTerms()->delete();
105     }
106
107     /**
108      * Create a scored term array from the given text, where the keys are the terms
109      * and the values are their scores.
110      *
111      * @returns array<string, int>
112      */
113     protected function generateTermScoreMapFromText(string $text, int $scoreAdjustment = 1): array
114     {
115         $termMap = $this->textToTermCountMap($text);
116
117         foreach ($termMap as $term => $count) {
118             $termMap[$term] = $count * $scoreAdjustment;
119         }
120
121         return $termMap;
122     }
123
124     /**
125      * Create a scored term array from the given HTML, where the keys are the terms
126      * and the values are their scores.
127      *
128      * @returns array<string, int>
129      */
130     protected function generateTermScoreMapFromHtml(string $html): array
131     {
132         if (empty($html)) {
133             return [];
134         }
135
136         $scoresByTerm = [];
137         $elementScoreAdjustmentMap = [
138             'h1' => 10,
139             'h2' => 5,
140             'h3' => 4,
141             'h4' => 3,
142             'h5' => 2,
143             'h6' => 1.5,
144         ];
145
146         $html = '<body>' . $html . '</body>';
147         libxml_use_internal_errors(true);
148         $doc = new DOMDocument();
149         $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
150
151         $topElems = $doc->documentElement->childNodes->item(0)->childNodes;
152         /** @var DOMNode $child */
153         foreach ($topElems as $child) {
154             $nodeName = $child->nodeName;
155             $termCounts = $this->textToTermCountMap(trim($child->textContent));
156             foreach ($termCounts as $term => $count) {
157                 $scoreChange = $count * ($elementScoreAdjustmentMap[$nodeName] ?? 1);
158                 $scoresByTerm[$term] = ($scoresByTerm[$term] ?? 0) + $scoreChange;
159             }
160         }
161
162         return $scoresByTerm;
163     }
164
165     /**
166      * Create a scored term map from the given set of entity tags.
167      *
168      * @param Tag[] $tags
169      *
170      * @returns array<string, int>
171      */
172     protected function generateTermScoreMapFromTags(array $tags): array
173     {
174         $scoreMap = [];
175         $names = [];
176         $values = [];
177
178         foreach ($tags as $tag) {
179             $names[] = $tag->name;
180             $values[] = $tag->value;
181         }
182
183         $nameMap = $this->generateTermScoreMapFromText(implode(' ', $names), 3);
184         $valueMap = $this->generateTermScoreMapFromText(implode(' ', $values), 5);
185
186         return $this->mergeTermScoreMaps($nameMap, $valueMap);
187     }
188
189     /**
190      * For the given text, return an array where the keys are the unique term words
191      * and the values are the frequency of that term.
192      *
193      * @returns array<string, int>
194      */
195     protected function textToTermCountMap(string $text): array
196     {
197         $tokenMap = []; // {TextToken => OccurrenceCount}
198         $splitChars = static::$delimiters;
199         $token = strtok($text, $splitChars);
200
201         while ($token !== false) {
202             if (!isset($tokenMap[$token])) {
203                 $tokenMap[$token] = 0;
204             }
205             $tokenMap[$token]++;
206             $token = strtok($splitChars);
207         }
208
209         return $tokenMap;
210     }
211
212     /**
213      * For the given entity, Generate an array of term data details.
214      * Is the raw term data, not instances of SearchTerm models.
215      *
216      * @returns array{term: string, score: float, entity_id: int, entity_type: string}[]
217      */
218     protected function entityToTermDataArray(Entity $entity): array
219     {
220         $nameTermsMap = $this->generateTermScoreMapFromText($entity->name, 40 * $entity->searchFactor);
221         $tagTermsMap = $this->generateTermScoreMapFromTags($entity->tags->all());
222
223         if ($entity instanceof Page) {
224             $bodyTermsMap = $this->generateTermScoreMapFromHtml($entity->html);
225         } else {
226             $bodyTermsMap = $this->generateTermScoreMapFromText($entity->description ?? '', $entity->searchFactor);
227         }
228
229         $mergedScoreMap = $this->mergeTermScoreMaps($nameTermsMap, $bodyTermsMap, $tagTermsMap);
230
231         $dataArray = [];
232         $entityId = $entity->id;
233         $entityType = $entity->getMorphClass();
234         foreach ($mergedScoreMap as $term => $score) {
235             $dataArray[] = [
236                 'term'        => $term,
237                 'score'       => $score,
238                 'entity_type' => $entityType,
239                 'entity_id'   => $entityId,
240             ];
241         }
242
243         return $dataArray;
244     }
245
246     /**
247      * For the given term data arrays, Merge their contents by term
248      * while combining any scores.
249      *
250      * @param array<string, int>[] ...$scoreMaps
251      *
252      * @returns array<string, int>
253      */
254     protected function mergeTermScoreMaps(...$scoreMaps): array
255     {
256         $mergedMap = [];
257
258         foreach ($scoreMaps as $scoreMap) {
259             foreach ($scoreMap as $term => $score) {
260                 $mergedMap[$term] = ($mergedMap[$term] ?? 0) + $score;
261             }
262         }
263
264         return $mergedMap;
265     }
266 }