3 namespace BookStack\Search;
5 use BookStack\Actions\Tag;
6 use BookStack\Entities\EntityProvider;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Entities\Models\Page;
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.
21 public static $delimiters = " \n\t.,!?:;()[]{}<>`'\"";
26 protected $entityProvider;
28 public function __construct(EntityProvider $entityProvider)
30 $this->entityProvider = $entityProvider;
34 * Index the given entity.
36 public function indexEntity(Entity $entity)
38 $this->deleteEntityTerms($entity);
39 $terms = $this->entityToTermDataArray($entity);
40 SearchTerm::query()->insert($terms);
44 * Index multiple Entities at once.
46 * @param Entity[] $entities
48 public function indexEntities(array $entities)
51 foreach ($entities as $entity) {
52 $entityTerms = $this->entityToTermDataArray($entity);
53 array_push($terms, ...$entityTerms);
56 $chunkedTerms = array_chunk($terms, 500);
57 foreach ($chunkedTerms as $termChunk) {
58 SearchTerm::query()->insert($termChunk);
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.
70 * @param callable(Entity, int, int):void|null $progressCallback
72 public function indexAllEntities(?callable $progressCallback = null)
74 SearchTerm::query()->truncate();
76 foreach ($this->entityProvider->all() as $entityModel) {
77 $indexContentField = $entityModel instanceof Page ? 'html' : 'description';
78 $selectFields = ['id', 'name', $indexContentField];
79 /** @var Builder<Entity> $query */
80 $query = $entityModel->newQuery();
81 $total = $query->withTrashed()->count();
85 $chunkCallback = function (Collection $entities) use ($progressCallback, &$processed, $total, $chunkSize, $entityModel) {
86 $this->indexEntities($entities->all());
87 $processed = min($processed + $chunkSize, $total);
89 if (is_callable($progressCallback)) {
90 $progressCallback($entityModel, $processed, $total);
94 $entityModel->newQuery()
95 ->select($selectFields)
96 ->with(['tags:id,name,value,entity_id,entity_type'])
97 ->chunk($chunkSize, $chunkCallback);
102 * Delete related Entity search terms.
104 public function deleteEntityTerms(Entity $entity)
106 $entity->searchTerms()->delete();
110 * Create a scored term array from the given text, where the keys are the terms
111 * and the values are their scores.
113 * @returns array<string, int>
115 protected function generateTermScoreMapFromText(string $text, int $scoreAdjustment = 1): array
117 $termMap = $this->textToTermCountMap($text);
119 foreach ($termMap as $term => $count) {
120 $termMap[$term] = $count * $scoreAdjustment;
127 * Create a scored term array from the given HTML, where the keys are the terms
128 * and the values are their scores.
130 * @returns array<string, int>
132 protected function generateTermScoreMapFromHtml(string $html): array
139 $elementScoreAdjustmentMap = [
148 $html = '<body>' . $html . '</body>';
149 $html = str_ireplace(['<br>', '<br />', '<br/>'], "\n", $html);
151 libxml_use_internal_errors(true);
152 $doc = new DOMDocument();
153 $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
155 $topElems = $doc->documentElement->childNodes->item(0)->childNodes;
156 /** @var DOMNode $child */
157 foreach ($topElems as $child) {
158 $nodeName = $child->nodeName;
159 $termCounts = $this->textToTermCountMap(trim($child->textContent));
160 foreach ($termCounts as $term => $count) {
161 $scoreChange = $count * ($elementScoreAdjustmentMap[$nodeName] ?? 1);
162 $scoresByTerm[$term] = ($scoresByTerm[$term] ?? 0) + $scoreChange;
166 return $scoresByTerm;
170 * Create a scored term map from the given set of entity tags.
174 * @returns array<string, int>
176 protected function generateTermScoreMapFromTags(array $tags): array
182 foreach ($tags as $tag) {
183 $names[] = $tag->name;
184 $values[] = $tag->value;
187 $nameMap = $this->generateTermScoreMapFromText(implode(' ', $names), 3);
188 $valueMap = $this->generateTermScoreMapFromText(implode(' ', $values), 5);
190 return $this->mergeTermScoreMaps($nameMap, $valueMap);
194 * For the given text, return an array where the keys are the unique term words
195 * and the values are the frequency of that term.
197 * @returns array<string, int>
199 protected function textToTermCountMap(string $text): array
201 $tokenMap = []; // {TextToken => OccurrenceCount}
202 $splitChars = static::$delimiters;
203 $token = strtok($text, $splitChars);
205 while ($token !== false) {
206 if (!isset($tokenMap[$token])) {
207 $tokenMap[$token] = 0;
210 $token = strtok($splitChars);
217 * For the given entity, Generate an array of term data details.
218 * Is the raw term data, not instances of SearchTerm models.
220 * @returns array{term: string, score: float, entity_id: int, entity_type: string}[]
222 protected function entityToTermDataArray(Entity $entity): array
224 $nameTermsMap = $this->generateTermScoreMapFromText($entity->name, 40 * $entity->searchFactor);
225 $tagTermsMap = $this->generateTermScoreMapFromTags($entity->tags->all());
227 if ($entity instanceof Page) {
228 $bodyTermsMap = $this->generateTermScoreMapFromHtml($entity->html);
230 $bodyTermsMap = $this->generateTermScoreMapFromText($entity->getAttribute('description') ?? '', $entity->searchFactor);
233 $mergedScoreMap = $this->mergeTermScoreMaps($nameTermsMap, $bodyTermsMap, $tagTermsMap);
236 $entityId = $entity->id;
237 $entityType = $entity->getMorphClass();
238 foreach ($mergedScoreMap as $term => $score) {
242 'entity_type' => $entityType,
243 'entity_id' => $entityId,
251 * For the given term data arrays, Merge their contents by term
252 * while combining any scores.
254 * @param array<string, int>[] ...$scoreMaps
256 * @returns array<string, int>
258 protected function mergeTermScoreMaps(...$scoreMaps): array
262 foreach ($scoreMaps as $scoreMap) {
263 foreach ($scoreMap as $term => $score) {
264 $mergedMap[$term] = ($mergedMap[$term] ?? 0) + $score;