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\Database\Eloquent\Builder;
13 use Illuminate\Support\Collection;
18 * A list of delimiter characters used to break-up parsed content into terms for indexing.
22 public static $delimiters = " \n\t.,!?:;()[]{}<>`'\"";
27 protected $entityProvider;
29 public function __construct(EntityProvider $entityProvider)
31 $this->entityProvider = $entityProvider;
35 * Index the given entity.
37 public function indexEntity(Entity $entity)
39 $this->deleteEntityTerms($entity);
40 $terms = $this->entityToTermDataArray($entity);
41 SearchTerm::query()->insert($terms);
45 * Index multiple Entities at once.
47 * @param Entity[] $entities
49 public function indexEntities(array $entities)
52 foreach ($entities as $entity) {
53 $entityTerms = $this->entityToTermDataArray($entity);
54 array_push($terms, ...$entityTerms);
57 $chunkedTerms = array_chunk($terms, 500);
58 foreach ($chunkedTerms as $termChunk) {
59 SearchTerm::query()->insert($termChunk);
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.
71 * @param callable(Entity, int, int):void|null $progressCallback
73 public function indexAllEntities(?callable $progressCallback = null)
75 SearchTerm::query()->truncate();
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();
86 $chunkCallback = function (Collection $entities) use ($progressCallback, &$processed, $total, $chunkSize, $entityModel) {
87 $this->indexEntities($entities->all());
88 $processed = min($processed + $chunkSize, $total);
90 if (is_callable($progressCallback)) {
91 $progressCallback($entityModel, $processed, $total);
95 $entityModel->newQuery()
96 ->select($selectFields)
97 ->with(['tags:id,name,value,entity_id,entity_type'])
98 ->chunk($chunkSize, $chunkCallback);
103 * Delete related Entity search terms.
105 public function deleteEntityTerms(Entity $entity)
107 $entity->searchTerms()->delete();
111 * Create a scored term array from the given text, where the keys are the terms
112 * and the values are their scores.
114 * @returns array<string, int>
116 protected function generateTermScoreMapFromText(string $text, int $scoreAdjustment = 1): array
118 $termMap = $this->textToTermCountMap($text);
120 foreach ($termMap as $term => $count) {
121 $termMap[$term] = $count * $scoreAdjustment;
128 * Create a scored term array from the given HTML, where the keys are the terms
129 * and the values are their scores.
131 * @returns array<string, int>
133 protected function generateTermScoreMapFromHtml(string $html): array
140 $elementScoreAdjustmentMap = [
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'));
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;
165 return $scoresByTerm;
169 * Create a scored term map from the given set of entity tags.
173 * @returns array<string, int>
175 protected function generateTermScoreMapFromTags(array $tags): array
181 foreach ($tags as $tag) {
182 $names[] = $tag->name;
183 $values[] = $tag->value;
186 $nameMap = $this->generateTermScoreMapFromText(implode(' ', $names), 3);
187 $valueMap = $this->generateTermScoreMapFromText(implode(' ', $values), 5);
189 return $this->mergeTermScoreMaps($nameMap, $valueMap);
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.
196 * @returns array<string, int>
198 protected function textToTermCountMap(string $text): array
200 $tokenMap = []; // {TextToken => OccurrenceCount}
201 $splitChars = static::$delimiters;
202 $token = strtok($text, $splitChars);
204 while ($token !== false) {
205 if (!isset($tokenMap[$token])) {
206 $tokenMap[$token] = 0;
209 $token = strtok($splitChars);
216 * For the given entity, Generate an array of term data details.
217 * Is the raw term data, not instances of SearchTerm models.
219 * @returns array{term: string, score: float, entity_id: int, entity_type: string}[]
221 protected function entityToTermDataArray(Entity $entity): array
223 $nameTermsMap = $this->generateTermScoreMapFromText($entity->name, 40 * $entity->searchFactor);
224 $tagTermsMap = $this->generateTermScoreMapFromTags($entity->tags->all());
226 if ($entity instanceof Page) {
227 $bodyTermsMap = $this->generateTermScoreMapFromHtml($entity->html);
229 $bodyTermsMap = $this->generateTermScoreMapFromText($entity->getAttribute('description') ?? '', $entity->searchFactor);
232 $mergedScoreMap = $this->mergeTermScoreMaps($nameTermsMap, $bodyTermsMap, $tagTermsMap);
235 $entityId = $entity->id;
236 $entityType = $entity->getMorphClass();
237 foreach ($mergedScoreMap as $term => $score) {
241 'entity_type' => $entityType,
242 'entity_id' => $entityId,
250 * For the given term data arrays, Merge their contents by term
251 * while combining any scores.
253 * @param array<string, int>[] ...$scoreMaps
255 * @returns array<string, int>
257 protected function mergeTermScoreMaps(...$scoreMaps): array
261 foreach ($scoreMaps as $scoreMap) {
262 foreach ($scoreMap as $term => $score) {
263 $mergedMap[$term] = ($mergedMap[$term] ?? 0) + $score;