3 namespace BookStack\Entities\Tools;
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;
12 use Illuminate\Support\Collection;
20 protected $entityProvider;
22 public function __construct(EntityProvider $entityProvider)
24 $this->entityProvider = $entityProvider;
28 * Index the given entity.
30 public function indexEntity(Entity $entity)
32 $this->deleteEntityTerms($entity);
33 $terms = $this->entityToTermDataArray($entity);
34 SearchTerm::query()->insert($terms);
38 * Index multiple Entities at once.
40 * @param Entity[] $entities
42 public function indexEntities(array $entities)
45 foreach ($entities as $entity) {
46 $entityTerms = $this->entityToTermDataArray($entity);
47 array_push($terms, ...$entityTerms);
50 $chunkedTerms = array_chunk($terms, 500);
51 foreach ($chunkedTerms as $termChunk) {
52 SearchTerm::query()->insert($termChunk);
57 * Delete and re-index the terms for all entities in the system.
58 * Can take a callback which is used for reporting progress.
59 * Callback receives three arguments:
60 * - An instance of the model being processed
61 * - The number that have been processed so far.
62 * - The total number of that model to be processed.
64 * @param callable(Entity, int, int)|null $progressCallback
66 public function indexAllEntities(?callable $progressCallback = null)
68 SearchTerm::query()->truncate();
70 foreach ($this->entityProvider->all() as $entityModel) {
71 $indexContentField = $entityModel instanceof Page ? 'html' : 'description';
72 $selectFields = ['id', 'name', $indexContentField];
73 $total = $entityModel->newQuery()->withTrashed()->count();
77 $chunkCallback = function (Collection $entities) use ($progressCallback, &$processed, $total, $chunkSize, $entityModel) {
78 $this->indexEntities($entities->all());
79 $processed = min($processed + $chunkSize, $total);
81 if (is_callable($progressCallback)) {
82 $progressCallback($entityModel, $processed, $total);
86 $entityModel->newQuery()
87 ->select($selectFields)
88 ->with(['tags:id,name,value,entity_id,entity_type'])
89 ->chunk($chunkSize, $chunkCallback);
94 * Delete related Entity search terms.
96 public function deleteEntityTerms(Entity $entity)
98 $entity->searchTerms()->delete();
102 * Create a scored term array from the given text, where the keys are the terms
103 * and the values are their scores.
105 * @returns array<string, int>
107 protected function generateTermScoreMapFromText(string $text, int $scoreAdjustment = 1): array
109 $termMap = $this->textToTermCountMap($text);
111 foreach ($termMap as $term => $count) {
112 $termMap[$term] = $count * $scoreAdjustment;
119 * Create a scored term array from the given HTML, where the keys are the terms
120 * and the values are their scores.
122 * @returns array<string, int>
124 protected function generateTermScoreMapFromHtml(string $html): array
131 $elementScoreAdjustmentMap = [
140 $html = '<body>' . $html . '</body>';
141 libxml_use_internal_errors(true);
142 $doc = new DOMDocument();
143 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
145 $topElems = $doc->documentElement->childNodes->item(0)->childNodes;
146 /** @var DOMNode $child */
147 foreach ($topElems as $child) {
148 $nodeName = $child->nodeName;
149 $termCounts = $this->textToTermCountMap(trim($child->textContent));
150 foreach ($termCounts as $term => $count) {
151 $scoreChange = $count * ($elementScoreAdjustmentMap[$nodeName] ?? 1);
152 $scoresByTerm[$term] = ($scoresByTerm[$term] ?? 0) + $scoreChange;
156 return $scoresByTerm;
160 * Create a scored term map from the given set of entity tags.
164 * @returns array<string, int>
166 protected function generateTermScoreMapFromTags(array $tags): array
172 foreach($tags as $tag) {
173 $names[] = $tag->name;
174 $values[] = $tag->value;
177 $nameMap = $this->generateTermScoreMapFromText(implode(' ', $names), 3);
178 $valueMap = $this->generateTermScoreMapFromText(implode(' ', $values), 5);
180 return $this->mergeTermScoreMaps($nameMap, $valueMap);
184 * For the given text, return an array where the keys are the unique term words
185 * and the values are the frequency of that term.
187 * @returns array<string, int>
189 protected function textToTermCountMap(string $text): array
191 $tokenMap = []; // {TextToken => OccurrenceCount}
192 $splitChars = " \n\t.,!?:;()[]{}<>`'\"";
193 $token = strtok($text, $splitChars);
195 while ($token !== false) {
196 if (!isset($tokenMap[$token])) {
197 $tokenMap[$token] = 0;
200 $token = strtok($splitChars);
207 * For the given entity, Generate an array of term data details.
208 * Is the raw term data, not instances of SearchTerm models.
210 * @returns array{term: string, score: float, entity_id: int, entity_type: string}[]
212 protected function entityToTermDataArray(Entity $entity): array
214 $nameTermsMap = $this->generateTermScoreMapFromText($entity->name, 40 * $entity->searchFactor);
215 $tagTermsMap = $this->generateTermScoreMapFromTags($entity->tags->all());
217 if ($entity instanceof Page) {
218 $bodyTermsMap = $this->generateTermScoreMapFromHtml($entity->html);
220 $bodyTermsMap = $this->generateTermScoreMapFromText($entity->description, $entity->searchFactor);
223 $mergedScoreMap = $this->mergeTermScoreMaps($nameTermsMap, $bodyTermsMap, $tagTermsMap);
226 $entityId = $entity->id;
227 $entityType = $entity->getMorphClass();
228 foreach ($mergedScoreMap as $term => $score) {
232 'entity_type' => $entityType,
233 'entity_id' => $entityId,
242 * For the given term data arrays, Merge their contents by term
243 * while combining any scores.
245 * @param array<string, int>[] ...$scoreMaps
247 * @returns array<string, int>
249 protected function mergeTermScoreMaps(...$scoreMaps): array
253 foreach ($scoreMaps as $scoreMap) {
254 foreach ($scoreMap as $term => $score) {
255 $mergedMap[$term] = ($mergedMap[$term] ?? 0) + $score;