3 namespace BookStack\Search;
5 use BookStack\Activity\Models\Tag;
6 use BookStack\Entities\Models\Entity;
7 use Illuminate\Support\HtmlString;
9 class SearchResultsFormatter
12 * For the given array of entities, Prepare the models to be shown in search result
13 * output. This sets a series of additional attributes.
15 * @param Entity[] $results
17 public function format(array $results, SearchOptions $options): void
19 foreach ($results as $result) {
20 $this->setSearchPreview($result, $options);
25 * Update the given entity model to set attributes used for previews of the item
26 * primarily within search result lists.
28 protected function setSearchPreview(Entity $entity, SearchOptions $options)
30 $textProperty = $entity->textField;
31 $textContent = $entity->$textProperty;
32 $terms = array_merge($options->exacts, $options->searches);
34 $originalContentByNewAttribute = [
35 'preview_name' => $entity->name,
36 'preview_content' => $textContent,
39 foreach ($originalContentByNewAttribute as $attributeName => $content) {
40 $targetLength = ($attributeName === 'preview_name') ? 0 : 260;
41 $matchRefs = $this->getMatchPositions($content, $terms);
42 $mergedRefs = $this->sortAndMergeMatchPositions($matchRefs);
43 $formatted = $this->formatTextUsingMatchPositions($mergedRefs, $content, $targetLength);
44 $entity->setAttribute($attributeName, new HtmlString($formatted));
47 $tags = $entity->relationLoaded('tags') ? $entity->tags->all() : [];
48 $this->highlightTagsContainingTerms($tags, $terms);
52 * Highlight tags which match the given terms.
55 * @param string[] $terms
57 protected function highlightTagsContainingTerms(array $tags, array $terms): void
59 foreach ($tags as $tag) {
60 $tagName = mb_strtolower($tag->name);
61 $tagValue = mb_strtolower($tag->value);
63 foreach ($terms as $term) {
64 $termLower = mb_strtolower($term);
66 if (mb_strpos($tagName, $termLower) !== false) {
67 $tag->setAttribute('highlight_name', true);
70 if (mb_strpos($tagValue, $termLower) !== false) {
71 $tag->setAttribute('highlight_value', true);
78 * Get positions of the given terms within the given text.
79 * Is in the array format of [int $startIndex => int $endIndex] where the indexes
80 * are positions within the provided text.
82 * @return array<int, int>
84 protected function getMatchPositions(string $text, array $terms): array
87 $text = mb_strtolower($text);
89 foreach ($terms as $term) {
91 $term = mb_strtolower($term);
92 $pos = mb_strpos($text, $term, $offset);
93 while ($pos !== false) {
94 $end = $pos + mb_strlen($term);
95 $matchRefs[$pos] = $end;
97 $pos = mb_strpos($text, $term, $offset);
105 * Sort the given match positions before merging them where they're
106 * adjacent or where they overlap.
108 * @param array<int, int> $matchPositions
110 * @return array<int, int>
112 protected function sortAndMergeMatchPositions(array $matchPositions): array
114 ksort($matchPositions);
119 foreach ($matchPositions as $start => $end) {
120 if ($start > $lastEnd) {
121 $mergedRefs[$start] = $end;
124 } elseif ($end > $lastEnd) {
125 $mergedRefs[$lastStart] = $end;
134 * Format the given original text, returning a version where terms are highlighted within.
135 * Returned content is in HTML text format.
136 * A given $targetLength of 0 asserts no target length limit.
138 * This is a complex function but written to be relatively efficient, going through the term matches in order
139 * so that we're only doing a one-time loop through of the matches. There is no further searching
142 protected function formatTextUsingMatchPositions(array $matchPositions, string $originalText, int $targetLength): string
144 $maxEnd = mb_strlen($originalText);
145 $fetchAll = ($targetLength === 0);
146 $contextLength = ($fetchAll ? 0 : 32);
151 $contentTextLength = 0;
154 $targetLength = $maxEnd * 2;
157 foreach ($matchPositions as $start => $end) {
158 // Get our outer text ranges for the added context we want to show upon the result.
159 $contextStart = max($start - $contextLength, 0, $lastEnd);
160 $contextEnd = min($end + $contextLength, $maxEnd);
162 // Adjust the start if we're going to be touching the previous match.
163 $startDiff = $start - $lastEnd;
164 if ($startDiff < 0) {
165 $contextStart = $start;
166 // Trims off '$startDiff' number of characters to bring it back to the start
167 // if this current match zone.
168 $content = mb_substr($content, 0, mb_strlen($content) + $startDiff);
169 $contentTextLength += $startDiff;
172 // Add ellipsis between results
173 if (!$fetchAll && $contextStart !== 0 && $contextStart !== $start) {
175 $contentTextLength += 4;
176 } elseif ($fetchAll) {
177 // Or fill in gap since the previous match
178 $fillLength = $contextStart - $lastEnd;
179 $content .= e(mb_substr($originalText, $lastEnd, $fillLength));
180 $contentTextLength += $fillLength;
183 // Add our content including the bolded matching text
184 $content .= e(mb_substr($originalText, $contextStart, $start - $contextStart));
185 $contentTextLength += $start - $contextStart;
186 $content .= '<strong>' . e(mb_substr($originalText, $start, $end - $start)) . '</strong>';
187 $contentTextLength += $end - $start;
188 $content .= e(mb_substr($originalText, $end, $contextEnd - $end));
189 $contentTextLength += $contextEnd - $end;
191 // Update our last end position
192 $lastEnd = $contextEnd;
194 // Update the first start position if it's not already been set
195 if (is_null($firstStart)) {
196 $firstStart = $contextStart;
199 // Stop if we're near our target
200 if ($contentTextLength >= $targetLength - 10) {
205 // Just copy out the content if we haven't moved along anywhere.
206 if ($lastEnd === 0) {
207 $content = e(mb_substr($originalText, 0, $targetLength));
208 $contentTextLength = $targetLength;
209 $lastEnd = $targetLength;
212 // Pad out the end if we're low
213 $remainder = $targetLength - $contentTextLength;
214 if ($remainder > 10) {
215 $padEndLength = min($maxEnd - $lastEnd, $remainder);
216 $content .= e(mb_substr($originalText, $lastEnd, $padEndLength));
217 $lastEnd += $padEndLength;
218 $contentTextLength += $padEndLength;
221 // Pad out the start if we're still low
222 $remainder = $targetLength - $contentTextLength;
223 $firstStart = $firstStart ?: 0;
224 if (!$fetchAll && $remainder > 10 && $firstStart !== 0) {
225 $padStart = max(0, $firstStart - $remainder);
226 $content = ($padStart === 0 ? '' : '...') . e(mb_substr($originalText, $padStart, $firstStart - $padStart)) . mb_substr($content, 4);
229 // Add ellipsis if we're not at the end
230 if ($lastEnd < $maxEnd) {