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