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