]> BookStack Code Mirror - bookstack/blob - app/Entities/SearchService.php
Checked over recycle bin parent/child flows
[bookstack] / app / Entities / SearchService.php
1 <?php namespace BookStack\Entities;
2
3 use BookStack\Auth\Permissions\PermissionService;
4 use Illuminate\Database\Connection;
5 use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
6 use Illuminate\Database\Query\Builder;
7 use Illuminate\Database\Query\JoinClause;
8 use Illuminate\Support\Collection;
9 use Illuminate\Support\Str;
10
11 class SearchService
12 {
13     /**
14      * @var SearchTerm
15      */
16     protected $searchTerm;
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     /**
35      * Acceptable operators to be used in a query
36      * @var array
37      */
38     protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
39
40     /**
41      * SearchService constructor.
42      */
43     public function __construct(SearchTerm $searchTerm, EntityProvider $entityProvider, Connection $db, PermissionService $permissionService)
44     {
45         $this->searchTerm = $searchTerm;
46         $this->entityProvider = $entityProvider;
47         $this->db = $db;
48         $this->permissionService = $permissionService;
49     }
50
51     /**
52      * Set the database connection
53      */
54     public function setConnection(Connection $connection)
55     {
56         $this->db = $connection;
57     }
58
59     /**
60      * Search all entities in the system.
61      * The provided count is for each entity to search,
62      * Total returned could can be larger and not guaranteed.
63      */
64     public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20, string $action = 'view'): array
65     {
66         $entityTypes = array_keys($this->entityProvider->all());
67         $entityTypesToSearch = $entityTypes;
68
69         if ($entityType !== 'all') {
70             $entityTypesToSearch = $entityType;
71         } else if (isset($searchOpts->filters['type'])) {
72             $entityTypesToSearch = explode('|', $searchOpts->filters['type']);
73         }
74
75         $results = collect();
76         $total = 0;
77         $hasMore = false;
78
79         foreach ($entityTypesToSearch as $entityType) {
80             if (!in_array($entityType, $entityTypes)) {
81                 continue;
82             }
83             $search = $this->searchEntityTable($searchOpts, $entityType, $page, $count, $action);
84             $entityTotal = $this->searchEntityTable($searchOpts, $entityType, $page, $count, $action, true);
85             if ($entityTotal > $page * $count) {
86                 $hasMore = true;
87             }
88             $total += $entityTotal;
89             $results = $results->merge($search);
90         }
91
92         return [
93             'total' => $total,
94             'count' => count($results),
95             'has_more' => $hasMore,
96             'results' => $results->sortByDesc('score')->values(),
97         ];
98     }
99
100
101     /**
102      * Search a book for entities
103      */
104     public function searchBook(int $bookId, string $searchString): Collection
105     {
106         $opts = SearchOptions::fromString($searchString);
107         $entityTypes = ['page', 'chapter'];
108         $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
109
110         $results = collect();
111         foreach ($entityTypesToSearch as $entityType) {
112             if (!in_array($entityType, $entityTypes)) {
113                 continue;
114             }
115             $search = $this->buildEntitySearchQuery($opts, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
116             $results = $results->merge($search);
117         }
118         return $results->sortByDesc('score')->take(20);
119     }
120
121     /**
122      * Search a book for entities
123      */
124     public function searchChapter(int $chapterId, string $searchString): Collection
125     {
126         $opts = SearchOptions::fromString($searchString);
127         $pages = $this->buildEntitySearchQuery($opts, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
128         return $pages->sortByDesc('score');
129     }
130
131     /**
132      * Search across a particular entity type.
133      * Setting getCount = true will return the total
134      * matching instead of the items themselves.
135      * @return \Illuminate\Database\Eloquent\Collection|int|static[]
136      */
137     public function searchEntityTable(SearchOptions $searchOpts, string $entityType = 'page', int $page = 1, int $count = 20, string $action = 'view', bool $getCount = false)
138     {
139         $query = $this->buildEntitySearchQuery($searchOpts, $entityType, $action);
140         if ($getCount) {
141             return $query->count();
142         }
143
144         $query = $query->skip(($page-1) * $count)->take($count);
145         return $query->get();
146     }
147
148     /**
149      * Create a search query for an entity
150      */
151     protected function buildEntitySearchQuery(SearchOptions $searchOpts, string $entityType = 'page', string $action = 'view'): EloquentBuilder
152     {
153         $entity = $this->entityProvider->get($entityType);
154         $entitySelect = $entity->newQuery();
155
156         // Handle normal search terms
157         if (count($searchOpts->searches) > 0) {
158             $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', \DB::raw('SUM(score) as score'));
159             $subQuery->where('entity_type', '=', $entity->getMorphClass());
160             $subQuery->where(function (Builder $query) use ($searchOpts) {
161                 foreach ($searchOpts->searches as $inputTerm) {
162                     $query->orWhere('term', 'like', $inputTerm .'%');
163                 }
164             })->groupBy('entity_type', 'entity_id');
165             $entitySelect->join(\DB::raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) {
166                 $join->on('id', '=', 'entity_id');
167             })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
168             $entitySelect->mergeBindings($subQuery);
169         }
170
171         // Handle exact term matching
172         if (count($searchOpts->exacts) > 0) {
173             $entitySelect->where(function (EloquentBuilder $query) use ($searchOpts, $entity) {
174                 foreach ($searchOpts->exacts as $inputTerm) {
175                     $query->where(function (EloquentBuilder $query) use ($inputTerm, $entity) {
176                         $query->where('name', 'like', '%'.$inputTerm .'%')
177                             ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
178                     });
179                 }
180             });
181         }
182
183         // Handle tag searches
184         foreach ($searchOpts->tags as $inputTerm) {
185             $this->applyTagSearch($entitySelect, $inputTerm);
186         }
187
188         // Handle filters
189         foreach ($searchOpts->filters as $filterTerm => $filterValue) {
190             $functionName = Str::camel('filter_' . $filterTerm);
191             if (method_exists($this, $functionName)) {
192                 $this->$functionName($entitySelect, $entity, $filterValue);
193             }
194         }
195
196         return $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, $action);
197     }
198
199     /**
200      * Get the available query operators as a regex escaped list.
201      */
202     protected function getRegexEscapedOperators(): string
203     {
204         $escapedOperators = [];
205         foreach ($this->queryOperators as $operator) {
206             $escapedOperators[] = preg_quote($operator);
207         }
208         return join('|', $escapedOperators);
209     }
210
211     /**
212      * Apply a tag search term onto a entity query.
213      */
214     protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
215     {
216         preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
217         $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
218             $tagName = $tagSplit[1];
219             $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
220             $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
221             $validOperator = in_array($tagOperator, $this->queryOperators);
222             if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
223                 if (!empty($tagName)) {
224                     $query->where('name', '=', $tagName);
225                 }
226                 if (is_numeric($tagValue) && $tagOperator !== 'like') {
227                     // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
228                     // search the value as a string which prevents being able to do number-based operations
229                     // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
230                     $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
231                     $query->whereRaw("value ${tagOperator} ${tagValue}");
232                 } else {
233                     $query->where('value', $tagOperator, $tagValue);
234                 }
235             } else {
236                 $query->where('name', '=', $tagName);
237             }
238         });
239         return $query;
240     }
241
242     /**
243      * Index the given entity.
244      */
245     public function indexEntity(Entity $entity)
246     {
247         $this->deleteEntityTerms($entity);
248         $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
249         $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
250         $terms = array_merge($nameTerms, $bodyTerms);
251         foreach ($terms as $index => $term) {
252             $terms[$index]['entity_type'] = $entity->getMorphClass();
253             $terms[$index]['entity_id'] = $entity->id;
254         }
255         $this->searchTerm->newQuery()->insert($terms);
256     }
257
258     /**
259      * Index multiple Entities at once
260      * @param \BookStack\Entities\Entity[] $entities
261      */
262     protected function indexEntities($entities)
263     {
264         $terms = [];
265         foreach ($entities as $entity) {
266             $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
267             $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
268             foreach (array_merge($nameTerms, $bodyTerms) as $term) {
269                 $term['entity_id'] = $entity->id;
270                 $term['entity_type'] = $entity->getMorphClass();
271                 $terms[] = $term;
272             }
273         }
274
275         $chunkedTerms = array_chunk($terms, 500);
276         foreach ($chunkedTerms as $termChunk) {
277             $this->searchTerm->newQuery()->insert($termChunk);
278         }
279     }
280
281     /**
282      * Delete and re-index the terms for all entities in the system.
283      */
284     public function indexAllEntities()
285     {
286         $this->searchTerm->truncate();
287
288         foreach ($this->entityProvider->all() as $entityModel) {
289             $selectFields = ['id', 'name', $entityModel->textField];
290             $entityModel->newQuery()
291                 ->withTrashed()
292                 ->select($selectFields)
293                 ->chunk(1000, function ($entities) {
294                     $this->indexEntities($entities);
295                 });
296         }
297     }
298
299     /**
300      * Delete related Entity search terms.
301      * @param Entity $entity
302      */
303     public function deleteEntityTerms(Entity $entity)
304     {
305         $entity->searchTerms()->delete();
306     }
307
308     /**
309      * Create a scored term array from the given text.
310      * @param $text
311      * @param float|int $scoreAdjustment
312      * @return array
313      */
314     protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
315     {
316         $tokenMap = []; // {TextToken => OccurrenceCount}
317         $splitChars = " \n\t.,!?:;()[]{}<>`'\"";
318         $token = strtok($text, $splitChars);
319
320         while ($token !== false) {
321             if (!isset($tokenMap[$token])) {
322                 $tokenMap[$token] = 0;
323             }
324             $tokenMap[$token]++;
325             $token = strtok($splitChars);
326         }
327
328         $terms = [];
329         foreach ($tokenMap as $token => $count) {
330             $terms[] = [
331                 'term' => $token,
332                 'score' => $count * $scoreAdjustment
333             ];
334         }
335         return $terms;
336     }
337
338
339
340
341     /**
342      * Custom entity search filters
343      */
344
345     protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input)
346     {
347         try {
348             $date = date_create($input);
349         } catch (\Exception $e) {
350             return;
351         }
352         $query->where('updated_at', '>=', $date);
353     }
354
355     protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input)
356     {
357         try {
358             $date = date_create($input);
359         } catch (\Exception $e) {
360             return;
361         }
362         $query->where('updated_at', '<', $date);
363     }
364
365     protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input)
366     {
367         try {
368             $date = date_create($input);
369         } catch (\Exception $e) {
370             return;
371         }
372         $query->where('created_at', '>=', $date);
373     }
374
375     protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
376     {
377         try {
378             $date = date_create($input);
379         } catch (\Exception $e) {
380             return;
381         }
382         $query->where('created_at', '<', $date);
383     }
384
385     protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
386     {
387         if (!is_numeric($input) && $input !== 'me') {
388             return;
389         }
390         if ($input === 'me') {
391             $input = user()->id;
392         }
393         $query->where('created_by', '=', $input);
394     }
395
396     protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
397     {
398         if (!is_numeric($input) && $input !== 'me') {
399             return;
400         }
401         if ($input === 'me') {
402             $input = user()->id;
403         }
404         $query->where('updated_by', '=', $input);
405     }
406
407     protected function filterInName(EloquentBuilder $query, Entity $model, $input)
408     {
409         $query->where('name', 'like', '%' .$input. '%');
410     }
411
412     protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
413     {
414         $this->filterInName($query, $model, $input);
415     }
416
417     protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
418     {
419         $query->where($model->textField, 'like', '%' .$input. '%');
420     }
421
422     protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
423     {
424         $query->where('restricted', '=', true);
425     }
426
427     protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
428     {
429         $query->whereHas('views', function ($query) {
430             $query->where('user_id', '=', user()->id);
431         });
432     }
433
434     protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
435     {
436         $query->whereDoesntHave('views', function ($query) {
437             $query->where('user_id', '=', user()->id);
438         });
439     }
440
441     protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
442     {
443         $functionName = Str::camel('sort_by_' . $input);
444         if (method_exists($this, $functionName)) {
445             $this->$functionName($query, $model);
446         }
447     }
448
449
450     /**
451      * Sorting filter options
452      */
453
454     protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
455     {
456         $commentsTable = $this->db->getTablePrefix() . 'comments';
457         $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
458         $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');
459
460         $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');
461     }
462 }