]> BookStack Code Mirror - bookstack/blob - app/Search/SearchResultsFormatter.php
Played around with a new app structure
[bookstack] / app / Search / SearchResultsFormatter.php
1 <?php
2
3 namespace BookStack\Search;
4
5 use BookStack\Activity\Models\Tag;
6 use BookStack\Entities\Models\Entity;
7 use Illuminate\Support\HtmlString;
8
9 class SearchResultsFormatter
10 {
11     /**
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.
14      *
15      * @param Entity[] $results
16      */
17     public function format(array $results, SearchOptions $options): void
18     {
19         foreach ($results as $result) {
20             $this->setSearchPreview($result, $options);
21         }
22     }
23
24     /**
25      * Update the given entity model to set attributes used for previews of the item
26      * primarily within search result lists.
27      */
28     protected function setSearchPreview(Entity $entity, SearchOptions $options)
29     {
30         $textProperty = $entity->textField;
31         $textContent = $entity->$textProperty;
32         $terms = array_merge($options->exacts, $options->searches);
33
34         $originalContentByNewAttribute = [
35             'preview_name'    => $entity->name,
36             'preview_content' => $textContent,
37         ];
38
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));
45         }
46
47         $tags = $entity->relationLoaded('tags') ? $entity->tags->all() : [];
48         $this->highlightTagsContainingTerms($tags, $terms);
49     }
50
51     /**
52      * Highlight tags which match the given terms.
53      *
54      * @param Tag[]    $tags
55      * @param string[] $terms
56      */
57     protected function highlightTagsContainingTerms(array $tags, array $terms): void
58     {
59         foreach ($tags as $tag) {
60             $tagName = mb_strtolower($tag->name);
61             $tagValue = mb_strtolower($tag->value);
62
63             foreach ($terms as $term) {
64                 $termLower = mb_strtolower($term);
65
66                 if (mb_strpos($tagName, $termLower) !== false) {
67                     $tag->setAttribute('highlight_name', true);
68                 }
69
70                 if (mb_strpos($tagValue, $termLower) !== false) {
71                     $tag->setAttribute('highlight_value', true);
72                 }
73             }
74         }
75     }
76
77     /**
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.
81      *
82      * @return array<int, int>
83      */
84     protected function getMatchPositions(string $text, array $terms): array
85     {
86         $matchRefs = [];
87         $text = mb_strtolower($text);
88
89         foreach ($terms as $term) {
90             $offset = 0;
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;
96                 $offset = $end;
97                 $pos = mb_strpos($text, $term, $offset);
98             }
99         }
100
101         return $matchRefs;
102     }
103
104     /**
105      * Sort the given match positions before merging them where they're
106      * adjacent or where they overlap.
107      *
108      * @param array<int, int> $matchPositions
109      *
110      * @return array<int, int>
111      */
112     protected function sortAndMergeMatchPositions(array $matchPositions): array
113     {
114         ksort($matchPositions);
115         $mergedRefs = [];
116         $lastStart = 0;
117         $lastEnd = 0;
118
119         foreach ($matchPositions as $start => $end) {
120             if ($start > $lastEnd) {
121                 $mergedRefs[$start] = $end;
122                 $lastStart = $start;
123                 $lastEnd = $end;
124             } elseif ($end > $lastEnd) {
125                 $mergedRefs[$lastStart] = $end;
126                 $lastEnd = $end;
127             }
128         }
129
130         return $mergedRefs;
131     }
132
133     /**
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.
137      *
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
140      * done within here.
141      */
142     protected function formatTextUsingMatchPositions(array $matchPositions, string $originalText, int $targetLength): string
143     {
144         $maxEnd = mb_strlen($originalText);
145         $fetchAll = ($targetLength === 0);
146         $contextLength = ($fetchAll ? 0 : 32);
147
148         $firstStart = null;
149         $lastEnd = 0;
150         $content = '';
151         $contentTextLength = 0;
152
153         if ($fetchAll) {
154             $targetLength = $maxEnd * 2;
155         }
156
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);
161
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;
170             }
171
172             // Add ellipsis between results
173             if (!$fetchAll && $contextStart !== 0 && $contextStart !== $start) {
174                 $content .= ' ...';
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;
181             }
182
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;
190
191             // Update our last end position
192             $lastEnd = $contextEnd;
193
194             // Update the first start position if it's not already been set
195             if (is_null($firstStart)) {
196                 $firstStart = $contextStart;
197             }
198
199             // Stop if we're near our target
200             if ($contentTextLength >= $targetLength - 10) {
201                 break;
202             }
203         }
204
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;
210         }
211
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;
219         }
220
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);
227         }
228
229         // Add ellipsis if we're not at the end
230         if ($lastEnd < $maxEnd) {
231             $content .= '...';
232         }
233
234         return $content;
235     }
236 }