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