]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/SearchRunner.php
Added testing coverage for tag index
[bookstack] / app / Entities / Tools / SearchRunner.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
5 use BookStack\Auth\Permissions\PermissionService;
6 use BookStack\Auth\User;
7 use BookStack\Entities\EntityProvider;
8 use BookStack\Entities\Models\Entity;
9 use Illuminate\Database\Connection;
10 use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
11 use Illuminate\Database\Query\Builder;
12 use Illuminate\Database\Query\JoinClause;
13 use Illuminate\Support\Collection;
14 use Illuminate\Support\Str;
15
16 class SearchRunner
17 {
18     /**
19      * @var EntityProvider
20      */
21     protected $entityProvider;
22
23     /**
24      * @var Connection
25      */
26     protected $db;
27
28     /**
29      * @var PermissionService
30      */
31     protected $permissionService;
32
33     /**
34      * Acceptable operators to be used in a query.
35      *
36      * @var array
37      */
38     protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
39
40     public function __construct(EntityProvider $entityProvider, Connection $db, PermissionService $permissionService)
41     {
42         $this->entityProvider = $entityProvider;
43         $this->db = $db;
44         $this->permissionService = $permissionService;
45     }
46
47     /**
48      * Search all entities in the system.
49      * The provided count is for each entity to search,
50      * Total returned could be larger and not guaranteed.
51      */
52     public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20, string $action = 'view'): array
53     {
54         $entityTypes = array_keys($this->entityProvider->all());
55         $entityTypesToSearch = $entityTypes;
56
57         if ($entityType !== 'all') {
58             $entityTypesToSearch = $entityType;
59         } elseif (isset($searchOpts->filters['type'])) {
60             $entityTypesToSearch = explode('|', $searchOpts->filters['type']);
61         }
62
63         $results = collect();
64         $total = 0;
65         $hasMore = false;
66
67         foreach ($entityTypesToSearch as $entityType) {
68             if (!in_array($entityType, $entityTypes)) {
69                 continue;
70             }
71
72             $search = $this->searchEntityTable($searchOpts, $entityType, $page, $count, $action);
73             /** @var int $entityTotal */
74             $entityTotal = $this->searchEntityTable($searchOpts, $entityType, $page, $count, $action, true);
75
76             if ($entityTotal > ($page * $count)) {
77                 $hasMore = true;
78             }
79
80             $total += $entityTotal;
81             $results = $results->merge($search);
82         }
83
84         return [
85             'total'    => $total,
86             'count'    => count($results),
87             'has_more' => $hasMore,
88             'results'  => $results->sortByDesc('score')->values(),
89         ];
90     }
91
92     /**
93      * Search a book for entities.
94      */
95     public function searchBook(int $bookId, string $searchString): Collection
96     {
97         $opts = SearchOptions::fromString($searchString);
98         $entityTypes = ['page', 'chapter'];
99         $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
100
101         $results = collect();
102         foreach ($entityTypesToSearch as $entityType) {
103             if (!in_array($entityType, $entityTypes)) {
104                 continue;
105             }
106             $search = $this->buildEntitySearchQuery($opts, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
107             $results = $results->merge($search);
108         }
109
110         return $results->sortByDesc('score')->take(20);
111     }
112
113     /**
114      * Search a chapter for entities.
115      */
116     public function searchChapter(int $chapterId, string $searchString): Collection
117     {
118         $opts = SearchOptions::fromString($searchString);
119         $pages = $this->buildEntitySearchQuery($opts, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
120
121         return $pages->sortByDesc('score');
122     }
123
124     /**
125      * Search across a particular entity type.
126      * Setting getCount = true will return the total
127      * matching instead of the items themselves.
128      *
129      * @return \Illuminate\Database\Eloquent\Collection|int|static[]
130      */
131     protected function searchEntityTable(SearchOptions $searchOpts, string $entityType = 'page', int $page = 1, int $count = 20, string $action = 'view', bool $getCount = false)
132     {
133         $query = $this->buildEntitySearchQuery($searchOpts, $entityType, $action);
134         if ($getCount) {
135             return $query->count();
136         }
137
138         $query = $query->skip(($page - 1) * $count)->take($count);
139
140         return $query->get();
141     }
142
143     /**
144      * Create a search query for an entity.
145      */
146     protected function buildEntitySearchQuery(SearchOptions $searchOpts, string $entityType = 'page', string $action = 'view'): EloquentBuilder
147     {
148         $entity = $this->entityProvider->get($entityType);
149         $entitySelect = $entity->newQuery();
150
151         // Handle normal search terms
152         if (count($searchOpts->searches) > 0) {
153             $rawScoreSum = $this->db->raw('SUM(score) as score');
154             $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', $rawScoreSum);
155             $subQuery->where('entity_type', '=', $entity->getMorphClass());
156             $subQuery->where(function (Builder $query) use ($searchOpts) {
157                 foreach ($searchOpts->searches as $inputTerm) {
158                     $query->orWhere('term', 'like', $inputTerm . '%');
159                 }
160             })->groupBy('entity_type', 'entity_id');
161             $entitySelect->join($this->db->raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) {
162                 $join->on('id', '=', 'entity_id');
163             })->addSelect($entity->getTable() . '.*')
164                 ->selectRaw('s.score')
165                 ->orderBy('score', 'desc');
166             $entitySelect->mergeBindings($subQuery);
167         }
168
169         // Handle exact term matching
170         foreach ($searchOpts->exacts as $inputTerm) {
171             $entitySelect->where(function (EloquentBuilder $query) use ($inputTerm, $entity) {
172                 $query->where('name', 'like', '%' . $inputTerm . '%')
173                     ->orWhere($entity->textField, 'like', '%' . $inputTerm . '%');
174             });
175         }
176
177         // Handle tag searches
178         foreach ($searchOpts->tags as $inputTerm) {
179             $this->applyTagSearch($entitySelect, $inputTerm);
180         }
181
182         // Handle filters
183         foreach ($searchOpts->filters as $filterTerm => $filterValue) {
184             $functionName = Str::camel('filter_' . $filterTerm);
185             if (method_exists($this, $functionName)) {
186                 $this->$functionName($entitySelect, $entity, $filterValue);
187             }
188         }
189
190         return $this->permissionService->enforceEntityRestrictions($entity, $entitySelect, $action);
191     }
192
193     /**
194      * Get the available query operators as a regex escaped list.
195      */
196     protected function getRegexEscapedOperators(): string
197     {
198         $escapedOperators = [];
199         foreach ($this->queryOperators as $operator) {
200             $escapedOperators[] = preg_quote($operator);
201         }
202
203         return implode('|', $escapedOperators);
204     }
205
206     /**
207      * Apply a tag search term onto a entity query.
208      */
209     protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
210     {
211         preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit);
212         $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
213             $tagName = $tagSplit[1];
214             $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
215             $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
216             $validOperator = in_array($tagOperator, $this->queryOperators);
217             if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
218                 if (!empty($tagName)) {
219                     $query->where('name', '=', $tagName);
220                 }
221                 if (is_numeric($tagValue) && $tagOperator !== 'like') {
222                     // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
223                     // search the value as a string which prevents being able to do number-based operations
224                     // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
225                     $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
226                     $query->whereRaw("value ${tagOperator} ${tagValue}");
227                 } else {
228                     $query->where('value', $tagOperator, $tagValue);
229                 }
230             } else {
231                 $query->where('name', '=', $tagName);
232             }
233         });
234
235         return $query;
236     }
237
238     /**
239      * Custom entity search filters.
240      */
241     protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input)
242     {
243         try {
244             $date = date_create($input);
245         } catch (\Exception $e) {
246             return;
247         }
248         $query->where('updated_at', '>=', $date);
249     }
250
251     protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input)
252     {
253         try {
254             $date = date_create($input);
255         } catch (\Exception $e) {
256             return;
257         }
258         $query->where('updated_at', '<', $date);
259     }
260
261     protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input)
262     {
263         try {
264             $date = date_create($input);
265         } catch (\Exception $e) {
266             return;
267         }
268         $query->where('created_at', '>=', $date);
269     }
270
271     protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
272     {
273         try {
274             $date = date_create($input);
275         } catch (\Exception $e) {
276             return;
277         }
278         $query->where('created_at', '<', $date);
279     }
280
281     protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
282     {
283         $userSlug = $input === 'me' ? user()->slug : trim($input);
284         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
285         if ($user) {
286             $query->where('created_by', '=', $user->id);
287         }
288     }
289
290     protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
291     {
292         $userSlug = $input === 'me' ? user()->slug : trim($input);
293         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
294         if ($user) {
295             $query->where('updated_by', '=', $user->id);
296         }
297     }
298
299     protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
300     {
301         $userSlug = $input === 'me' ? user()->slug : trim($input);
302         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
303         if ($user) {
304             $query->where('owned_by', '=', $user->id);
305         }
306     }
307
308     protected function filterInName(EloquentBuilder $query, Entity $model, $input)
309     {
310         $query->where('name', 'like', '%' . $input . '%');
311     }
312
313     protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
314     {
315         $this->filterInName($query, $model, $input);
316     }
317
318     protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
319     {
320         $query->where($model->textField, 'like', '%' . $input . '%');
321     }
322
323     protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
324     {
325         $query->where('restricted', '=', true);
326     }
327
328     protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
329     {
330         $query->whereHas('views', function ($query) {
331             $query->where('user_id', '=', user()->id);
332         });
333     }
334
335     protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
336     {
337         $query->whereDoesntHave('views', function ($query) {
338             $query->where('user_id', '=', user()->id);
339         });
340     }
341
342     protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
343     {
344         $functionName = Str::camel('sort_by_' . $input);
345         if (method_exists($this, $functionName)) {
346             $this->$functionName($query, $model);
347         }
348     }
349
350     /**
351      * Sorting filter options.
352      */
353     protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
354     {
355         $commentsTable = $this->db->getTablePrefix() . 'comments';
356         $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
357         $commentQuery = $this->db->raw('(SELECT c1.entity_id, c1.entity_type, c1.created_at as last_commented FROM ' . $commentsTable . ' c1 LEFT JOIN ' . $commentsTable . ' c2 ON (c1.entity_id = c2.entity_id AND c1.entity_type = c2.entity_type AND c1.created_at < c2.created_at) WHERE c1.entity_type = \'' . $morphClass . '\' AND c2.created_at IS NULL) as comments');
358
359         $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');
360     }
361 }