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