3 namespace BookStack\Entities\Tools;
5 use BookStack\Actions\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 = strtolower($tag->name);
61 $tagValue = strtolower($tag->value);
63 foreach ($terms as $term) {
64 $termLower = strtolower($term);
66 if (strpos($tagName, $termLower) !== false) {
67 $tag->setAttribute('highlight_name', true);
70 if (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 = strtolower($text);
89 foreach ($terms as $term) {
91 $term = strtolower($term);
92 $pos = strpos($text, $term, $offset);
93 while ($pos !== false) {
94 $end = $pos + strlen($term);
95 $matchRefs[$pos] = $end;
97 $pos = 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
145 $maxEnd = strlen($originalText);
148 $fetchAll = ($targetLength === 0);
150 $contentTextLength = 0;
153 $targetLength = $maxEnd * 2;
156 foreach ($matchPositions as $start => $end) {
157 // Get our outer text ranges for the added context we want to show upon the result.
158 $contextStart = max($start - $contextRange, 0, $lastEnd);
159 $contextEnd = min($end + $contextRange, $maxEnd);
161 // Adjust the start if we're going to be touching the previous match.
162 $startDiff = $start - $lastEnd;
163 if ($startDiff < 0) {
164 $contextStart = $start;
165 // Trims off '$startDiff' number of characters to bring it back to the start
166 // if this current match zone.
167 $content = substr($content, 0, strlen($content) + $startDiff);
168 $contentTextLength += $startDiff;
171 // Add ellipsis between results
172 if (!$fetchAll && $contextStart !== 0 && $contextStart !== $start) {
174 $contentTextLength += 4;
175 } else if ($fetchAll) {
176 // Or fill in gap since the previous match
177 $fillLength = $contextStart - $lastEnd;
178 $content .= e(substr($originalText, $lastEnd, $fillLength));
179 $contentTextLength += $fillLength;
182 // Add our content including the bolded matching text
183 $content .= e(substr($originalText, $contextStart, $start - $contextStart));
184 $contentTextLength += $start - $contextStart;
185 $content .= '<strong>' . e(substr($originalText, $start, $end - $start)) . '</strong>';
186 $contentTextLength += $end - $start;
187 $content .= e(substr($originalText, $end, $contextEnd - $end));
188 $contentTextLength += $contextEnd - $end;
190 // Update our last end position
191 $lastEnd = $contextEnd;
193 // Update the first start position if it's not already been set
194 if (is_null($firstStart)) {
195 $firstStart = $contextStart;
198 // Stop if we're near our target
199 if ($contentTextLength >= $targetLength - 10) {
204 // Just copy out the content if we haven't moved along anywhere.
205 if ($lastEnd === 0) {
206 $content = e(substr($originalText, 0, $targetLength));
207 $contentTextLength = $targetLength;
208 $lastEnd = $targetLength;
211 // Pad out the end if we're low
212 $remainder = $targetLength - $contentTextLength;
213 if ($remainder > 10) {
214 $padEndLength = min($maxEnd - $lastEnd, $remainder);
215 $content .= e(substr($originalText, $lastEnd, $padEndLength));
216 $lastEnd += $padEndLength;
217 $contentTextLength += $padEndLength;
220 // Pad out the start if we're still low
221 $remainder = $targetLength - $contentTextLength;
222 $firstStart = $firstStart ?: 0;
223 if (!$fetchAll && $remainder > 10 && $firstStart !== 0) {
224 $padStart = max(0, $firstStart - $remainder);
225 $content = ($padStart === 0 ? '' : '...') . e(substr($originalText, $padStart, $firstStart - $padStart)) . substr($content, 4);
228 // Add ellipsis if we're not at the end
229 if ($lastEnd < $maxEnd) {