]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/SearchRunner.php
Allow to use DB tables prefix
[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             })->selectRaw($entity->getTable() . '.*, s.score')->orderBy('score', 'desc');
160             $entitySelect->mergeBindings($subQuery);
161         }
162
163         // Handle exact term matching
164         foreach ($searchOpts->exacts as $inputTerm) {
165             $entitySelect->where(function (EloquentBuilder $query) use ($inputTerm, $entity) {
166                 $query->where('name', 'like', '%' . $inputTerm . '%')
167                     ->orWhere($entity->textField, 'like', '%' . $inputTerm . '%');
168             });
169         }
170
171         // Handle tag searches
172         foreach ($searchOpts->tags as $inputTerm) {
173             $this->applyTagSearch($entitySelect, $inputTerm);
174         }
175
176         // Handle filters
177         foreach ($searchOpts->filters as $filterTerm => $filterValue) {
178             $functionName = Str::camel('filter_' . $filterTerm);
179             if (method_exists($this, $functionName)) {
180                 $this->$functionName($entitySelect, $entity, $filterValue);
181             }
182         }
183
184         return $this->permissionService->enforceEntityRestrictions($entity, $entitySelect, $action);
185     }
186
187     /**
188      * Get the available query operators as a regex escaped list.
189      */
190     protected function getRegexEscapedOperators(): string
191     {
192         $escapedOperators = [];
193         foreach ($this->queryOperators as $operator) {
194             $escapedOperators[] = preg_quote($operator);
195         }
196
197         return join('|', $escapedOperators);
198     }
199
200     /**
201      * Apply a tag search term onto a entity query.
202      */
203     protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
204     {
205         preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit);
206         $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
207             $tagName = $tagSplit[1];
208             $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
209             $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
210             $validOperator = in_array($tagOperator, $this->queryOperators);
211             if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
212                 if (!empty($tagName)) {
213                     $query->where('name', '=', $tagName);
214                 }
215                 if (is_numeric($tagValue) && $tagOperator !== 'like') {
216                     // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
217                     // search the value as a string which prevents being able to do number-based operations
218                     // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
219                     $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
220                     $query->whereRaw("value ${tagOperator} ${tagValue}");
221                 } else {
222                     $query->where('value', $tagOperator, $tagValue);
223                 }
224             } else {
225                 $query->where('name', '=', $tagName);
226             }
227         });
228
229         return $query;
230     }
231
232     /**
233      * Custom entity search filters.
234      */
235     protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input)
236     {
237         try {
238             $date = date_create($input);
239         } catch (\Exception $e) {
240             return;
241         }
242         $query->where('updated_at', '>=', $date);
243     }
244
245     protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input)
246     {
247         try {
248             $date = date_create($input);
249         } catch (\Exception $e) {
250             return;
251         }
252         $query->where('updated_at', '<', $date);
253     }
254
255     protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input)
256     {
257         try {
258             $date = date_create($input);
259         } catch (\Exception $e) {
260             return;
261         }
262         $query->where('created_at', '>=', $date);
263     }
264
265     protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
266     {
267         try {
268             $date = date_create($input);
269         } catch (\Exception $e) {
270             return;
271         }
272         $query->where('created_at', '<', $date);
273     }
274
275     protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
276     {
277         $userSlug = $input === 'me' ? user()->slug : trim($input);
278         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
279         if ($user) {
280             $query->where('created_by', '=', $user->id);
281         }
282     }
283
284     protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
285     {
286         $userSlug = $input === 'me' ? user()->slug : trim($input);
287         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
288         if ($user) {
289             $query->where('updated_by', '=', $user->id);
290         }
291     }
292
293     protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
294     {
295         $userSlug = $input === 'me' ? user()->slug : trim($input);
296         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
297         if ($user) {
298             $query->where('owned_by', '=', $user->id);
299         }
300     }
301
302     protected function filterInName(EloquentBuilder $query, Entity $model, $input)
303     {
304         $query->where('name', 'like', '%' . $input . '%');
305     }
306
307     protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
308     {
309         $this->filterInName($query, $model, $input);
310     }
311
312     protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
313     {
314         $query->where($model->textField, 'like', '%' . $input . '%');
315     }
316
317     protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
318     {
319         $query->where('restricted', '=', true);
320     }
321
322     protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
323     {
324         $query->whereHas('views', function ($query) {
325             $query->where('user_id', '=', user()->id);
326         });
327     }
328
329     protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
330     {
331         $query->whereDoesntHave('views', function ($query) {
332             $query->where('user_id', '=', user()->id);
333         });
334     }
335
336     protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
337     {
338         $functionName = Str::camel('sort_by_' . $input);
339         if (method_exists($this, $functionName)) {
340             $this->$functionName($query, $model);
341         }
342     }
343
344     /**
345      * Sorting filter options.
346      */
347     protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
348     {
349         $commentsTable = $this->db->getTablePrefix() . 'comments';
350         $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
351         $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');
352
353         $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');
354     }
355 }