]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/SearchResultsFormatter.php
1ddee5830c53456ddf7e1c092d8359eb06ad02a5
[bookstack] / app / Entities / Tools / SearchResultsFormatter.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use BookStack\Actions\Tag;
6 use BookStack\Entities\Models\Entity;
7 use Illuminate\Support\HtmlString;
8
9 class SearchResultsFormatter
10 {
11
12     /**
13      * For the given array of entities, Prepare the models to be shown in search result
14      * output. This sets a series of additional attributes.
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             $matchRefs = $this->getMatchPositions($content, $terms);
41             $mergedRefs = $this->sortAndMergeMatchPositions($matchRefs);
42             $formatted = $this->formatTextUsingMatchPositions($mergedRefs, $content);
43             $entity->setAttribute($attributeName, new HtmlString($formatted));
44         }
45
46         $tags = $entity->relationLoaded('tags') ? $entity->tags->all() : [];
47         $this->highlightTagsContainingTerms($tags, $terms);
48     }
49
50     /**
51      * Highlight tags which match the given terms.
52      * @param Tag[] $tags
53      * @param string[] $terms
54      */
55     protected function highlightTagsContainingTerms(array $tags, array $terms): void
56     {
57         foreach ($tags as $tag) {
58             $tagName = strtolower($tag->name);
59             $tagValue = strtolower($tag->value);
60
61             foreach ($terms as $term) {
62                 $termLower = strtolower($term);
63
64                 if (strpos($tagName, $termLower) !== false) {
65                     $tag->setAttribute('highlight_name', true);
66                 }
67
68                 if (strpos($tagValue, $termLower) !== false) {
69                     $tag->setAttribute('highlight_value', true);
70                 }
71             }
72         }
73     }
74
75     /**
76      * Get positions of the given terms within the given text.
77      * Is in the array format of [int $startIndex => int $endIndex] where the indexes
78      * are positions within the provided text.
79      *
80      * @return array<int, int>
81      */
82     protected function getMatchPositions(string $text, array $terms): array
83     {
84         $matchRefs = [];
85         $text = strtolower($text);
86
87         foreach ($terms as $term) {
88             $offset = 0;
89             $term = strtolower($term);
90             $pos = strpos($text, $term, $offset);
91             while ($pos !== false) {
92                 $end = $pos + strlen($term);
93                 $matchRefs[$pos] = $end;
94                 $offset = $end;
95                 $pos = strpos($text, $term, $offset);
96             }
97         }
98
99         return $matchRefs;
100     }
101
102     /**
103      * Sort the given match positions before merging them where they're
104      * adjacent or where they overlap.
105      *
106      * @param array<int, int> $matchPositions
107      * @return array<int, int>
108      */
109     protected function sortAndMergeMatchPositions(array $matchPositions): array
110     {
111         ksort($matchPositions);
112         $mergedRefs = [];
113         $lastStart = 0;
114         $lastEnd = 0;
115
116         foreach ($matchPositions as $start => $end) {
117             if ($start > $lastEnd) {
118                 $mergedRefs[$start] = $end;
119                 $lastStart = $start;
120                 $lastEnd = $end;
121             } else if ($end > $lastEnd) {
122                 $mergedRefs[$lastStart] = $end;
123                 $lastEnd = $end;
124             }
125         }
126
127         return $mergedRefs;
128     }
129
130     /**
131      * Format the given original text, returning a version where terms are highlighted within.
132      * Returned content is in HTML text format.
133      */
134     protected function formatTextUsingMatchPositions(array $matchPositions, string $originalText): string
135     {
136         $contextRange = 32;
137         $targetLength = 260;
138         $maxEnd = strlen($originalText);
139         $lastEnd = 0;
140         $firstStart = null;
141         $content = '';
142
143         foreach ($matchPositions as $start => $end) {
144             // Get our outer text ranges for the added context we want to show upon the result.
145             $contextStart = max($start - $contextRange, 0, $lastEnd);
146             $contextEnd = min($end + $contextRange, $maxEnd);
147
148             // Adjust the start if we're going to be touching the previous match.
149             $startDiff = $start - $lastEnd;
150             if ($startDiff < 0) {
151                 $contextStart = $start;
152                 $content = substr($content, 0, strlen($content) + $startDiff);
153             }
154
155             // Add ellipsis between results
156             if ($contextStart !== 0 && $contextStart !== $start) {
157                 $content .= ' ...';
158             }
159
160             // Add our content including the bolded matching text
161             $content .= e(substr($originalText, $contextStart, $start - $contextStart));
162             $content .= '<strong>' . e(substr($originalText, $start, $end - $start)) . '</strong>';
163             $content .= e(substr($originalText, $end, $contextEnd - $end));
164
165             // Update our last end position
166             $lastEnd = $contextEnd;
167
168             // Update the first start position if it's not already been set
169             if (is_null($firstStart)) {
170                 $firstStart = $contextStart;
171             }
172
173             // Stop if we're near our target
174             if (strlen($content) >= $targetLength - 10) {
175                 break;
176             }
177         }
178
179         // Just copy out the content if we haven't moved along anywhere.
180         if ($lastEnd === 0) {
181             $content = e(substr($originalText, 0, $targetLength));
182             $lastEnd = $targetLength;
183         }
184
185         // Pad out the end if we're low
186         $remainder = $targetLength - strlen($content);
187         if ($remainder > 10) {
188             $content .= e(substr($originalText, $lastEnd, $remainder));
189             $lastEnd += $remainder;
190         }
191
192         // Pad out the start if we're still low
193         $remainder = $targetLength - strlen($content);
194         $firstStart = $firstStart ?: 0;
195         if ($remainder > 10 && $firstStart !== 0) {
196             $padStart = max(0, $firstStart - $remainder);
197             $content = ($padStart === 0 ? '' : '...') . e(substr($originalText, $padStart,  $firstStart - $padStart)) . substr($content, 4);
198         }
199
200         // Add ellipsis if we're not at the end
201         if ($lastEnd < $maxEnd) {
202             $content .= '...';
203         }
204
205         return $content;
206     }
207
208 }