]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/SearchRunner.php
feat(PageContent): set unique ids on nested headers
[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\BookChild;
9 use BookStack\Entities\Models\Entity;
10 use BookStack\Entities\Models\Page;
11 use BookStack\Entities\Models\SearchTerm;
12 use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
13 use Illuminate\Database\Eloquent\Collection as EloquentCollection;
14 use Illuminate\Database\Eloquent\Relations\BelongsTo;
15 use Illuminate\Database\Query\Builder;
16 use Illuminate\Support\Collection;
17 use Illuminate\Support\Facades\DB;
18 use Illuminate\Support\Str;
19 use SplObjectStorage;
20
21 class SearchRunner
22 {
23     /**
24      * @var EntityProvider
25      */
26     protected $entityProvider;
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     /**
41      * Retain a cache of score adjusted terms for specific search options.
42      * From PHP>=8 this can be made into a WeakMap instead.
43      *
44      * @var SplObjectStorage
45      */
46     protected $termAdjustmentCache;
47
48     public function __construct(EntityProvider $entityProvider, PermissionService $permissionService)
49     {
50         $this->entityProvider = $entityProvider;
51         $this->permissionService = $permissionService;
52         $this->termAdjustmentCache = new SplObjectStorage();
53     }
54
55     /**
56      * Search all entities in the system.
57      * The provided count is for each entity to search,
58      * Total returned could be larger and not guaranteed.
59      *
60      * @return array{total: int, count: int, has_more: bool, results: Entity[]}
61      */
62     public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20, string $action = 'view'): array
63     {
64         $entityTypes = array_keys($this->entityProvider->all());
65         $entityTypesToSearch = $entityTypes;
66
67         if ($entityType !== 'all') {
68             $entityTypesToSearch = $entityType;
69         } elseif (isset($searchOpts->filters['type'])) {
70             $entityTypesToSearch = explode('|', $searchOpts->filters['type']);
71         }
72
73         $results = collect();
74         $total = 0;
75         $hasMore = false;
76
77         foreach ($entityTypesToSearch as $entityType) {
78             if (!in_array($entityType, $entityTypes)) {
79                 continue;
80             }
81
82             $entityModelInstance = $this->entityProvider->get($entityType);
83             $searchQuery = $this->buildQuery($searchOpts, $entityModelInstance, $action);
84             $entityTotal = $searchQuery->count();
85             $searchResults = $this->getPageOfDataFromQuery($searchQuery, $entityModelInstance, $page, $count);
86
87             if ($entityTotal > ($page * $count)) {
88                 $hasMore = true;
89             }
90
91             $total += $entityTotal;
92             $results = $results->merge($searchResults);
93         }
94
95         return [
96             'total'    => $total,
97             'count'    => count($results),
98             'has_more' => $hasMore,
99             'results'  => $results->sortByDesc('score')->values(),
100         ];
101     }
102
103     /**
104      * Search a book for entities.
105      */
106     public function searchBook(int $bookId, string $searchString): Collection
107     {
108         $opts = SearchOptions::fromString($searchString);
109         $entityTypes = ['page', 'chapter'];
110         $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
111
112         $results = collect();
113         foreach ($entityTypesToSearch as $entityType) {
114             if (!in_array($entityType, $entityTypes)) {
115                 continue;
116             }
117
118             $entityModelInstance = $this->entityProvider->get($entityType);
119             $search = $this->buildQuery($opts, $entityModelInstance)->where('book_id', '=', $bookId)->take(20)->get();
120             $results = $results->merge($search);
121         }
122
123         return $results->sortByDesc('score')->take(20);
124     }
125
126     /**
127      * Search a chapter for entities.
128      */
129     public function searchChapter(int $chapterId, string $searchString): Collection
130     {
131         $opts = SearchOptions::fromString($searchString);
132         $entityModelInstance = $this->entityProvider->get('page');
133         $pages = $this->buildQuery($opts, $entityModelInstance)->where('chapter_id', '=', $chapterId)->take(20)->get();
134
135         return $pages->sortByDesc('score');
136     }
137
138     /**
139      * Get a page of result data from the given query based on the provided page parameters.
140      */
141     protected function getPageOfDataFromQuery(EloquentBuilder $query, Entity $entityModelInstance, int $page = 1, int $count = 20): EloquentCollection
142     {
143         $relations = ['tags'];
144
145         if ($entityModelInstance instanceof BookChild) {
146             $relations['book'] = function (BelongsTo $query) {
147                 $query->visible();
148             };
149         }
150
151         if ($entityModelInstance instanceof Page) {
152             $relations['chapter'] = function (BelongsTo $query) {
153                 $query->visible();
154             };
155         }
156
157         return $query->clone()
158             ->with(array_filter($relations))
159             ->skip(($page - 1) * $count)
160             ->take($count)
161             ->get();
162     }
163
164     /**
165      * Create a search query for an entity.
166      */
167     protected function buildQuery(SearchOptions $searchOpts, Entity $entityModelInstance, string $action = 'view'): EloquentBuilder
168     {
169         $entityQuery = $entityModelInstance->newQuery();
170
171         if ($entityModelInstance instanceof Page) {
172             $entityQuery->select($entityModelInstance::$listAttributes);
173         } else {
174             $entityQuery->select(['*']);
175         }
176
177         // Handle normal search terms
178         $this->applyTermSearch($entityQuery, $searchOpts, $entityModelInstance);
179
180         // Handle exact term matching
181         foreach ($searchOpts->exacts as $inputTerm) {
182             $entityQuery->where(function (EloquentBuilder $query) use ($inputTerm, $entityModelInstance) {
183                 $query->where('name', 'like', '%' . $inputTerm . '%')
184                     ->orWhere($entityModelInstance->textField, 'like', '%' . $inputTerm . '%');
185             });
186         }
187
188         // Handle tag searches
189         foreach ($searchOpts->tags as $inputTerm) {
190             $this->applyTagSearch($entityQuery, $inputTerm);
191         }
192
193         // Handle filters
194         foreach ($searchOpts->filters as $filterTerm => $filterValue) {
195             $functionName = Str::camel('filter_' . $filterTerm);
196             if (method_exists($this, $functionName)) {
197                 $this->$functionName($entityQuery, $entityModelInstance, $filterValue);
198             }
199         }
200
201         return $this->permissionService->enforceEntityRestrictions($entityModelInstance, $entityQuery, $action);
202     }
203
204     /**
205      * For the given search query, apply the queries for handling the regular search terms.
206      */
207     protected function applyTermSearch(EloquentBuilder $entityQuery, SearchOptions $options, Entity $entity): void
208     {
209         $terms = $options->searches;
210         if (count($terms) === 0) {
211             return;
212         }
213
214         $scoredTerms = $this->getTermAdjustments($options);
215         $scoreSelect = $this->selectForScoredTerms($scoredTerms);
216
217         $subQuery = DB::table('search_terms')->select([
218             'entity_id',
219             'entity_type',
220             DB::raw($scoreSelect['statement']),
221         ]);
222
223         $subQuery->addBinding($scoreSelect['bindings'], 'select');
224
225         $subQuery->where('entity_type', '=', $entity->getMorphClass());
226         $subQuery->where(function (Builder $query) use ($terms) {
227             foreach ($terms as $inputTerm) {
228                 $query->orWhere('term', 'like', $inputTerm . '%');
229             }
230         });
231         $subQuery->groupBy('entity_type', 'entity_id');
232
233         $entityQuery->joinSub($subQuery, 's', 'id', '=', 'entity_id');
234         $entityQuery->addSelect('s.score');
235         $entityQuery->orderBy('score', 'desc');
236     }
237
238     /**
239      * Create a select statement, with prepared bindings, for the given
240      * set of scored search terms.
241      *
242      * @param array<string, float> $scoredTerms
243      *
244      * @return array{statement: string, bindings: string[]}
245      */
246     protected function selectForScoredTerms(array $scoredTerms): array
247     {
248         // Within this we walk backwards to create the chain of 'if' statements
249         // so that each previous statement is used in the 'else' condition of
250         // the next (earlier) to be built. We start at '0' to have no score
251         // on no match (Should never actually get to this case).
252         $ifChain = '0';
253         $bindings = [];
254         foreach ($scoredTerms as $term => $score) {
255             $ifChain = 'IF(term like ?, score * ' . (float) $score . ', ' . $ifChain . ')';
256             $bindings[] = $term . '%';
257         }
258
259         return [
260             'statement' => 'SUM(' . $ifChain . ') as score',
261             'bindings'  => array_reverse($bindings),
262         ];
263     }
264
265     /**
266      * For the terms in the given search options, query their popularity across all
267      * search terms then provide that back as score adjustment multiplier applicable
268      * for their rarity. Returns an array of float multipliers, keyed by term.
269      *
270      * @return array<string, float>
271      */
272     protected function getTermAdjustments(SearchOptions $options): array
273     {
274         if (isset($this->termAdjustmentCache[$options])) {
275             return $this->termAdjustmentCache[$options];
276         }
277
278         $termQuery = SearchTerm::query()->toBase();
279         $whenStatements = [];
280         $whenBindings = [];
281
282         foreach ($options->searches as $term) {
283             $whenStatements[] = 'WHEN term LIKE ? THEN ?';
284             $whenBindings[] = $term . '%';
285             $whenBindings[] = $term;
286
287             $termQuery->orWhere('term', 'like', $term . '%');
288         }
289
290         $case = 'CASE ' . implode(' ', $whenStatements) . ' END';
291         $termQuery->selectRaw($case . ' as term', $whenBindings);
292         $termQuery->selectRaw('COUNT(*) as count');
293         $termQuery->groupByRaw($case, $whenBindings);
294
295         $termCounts = $termQuery->pluck('count', 'term')->toArray();
296         $adjusted = $this->rawTermCountsToAdjustments($termCounts);
297
298         $this->termAdjustmentCache[$options] = $adjusted;
299
300         return $this->termAdjustmentCache[$options];
301     }
302
303     /**
304      * Convert counts of terms into a relative-count normalised multiplier.
305      *
306      * @param array<string, int> $termCounts
307      *
308      * @return array<string, int>
309      */
310     protected function rawTermCountsToAdjustments(array $termCounts): array
311     {
312         if (empty($termCounts)) {
313             return [];
314         }
315
316         $multipliers = [];
317         $max = max(array_values($termCounts));
318
319         foreach ($termCounts as $term => $count) {
320             $percent = round($count / $max, 5);
321             $multipliers[$term] = 1.3 - $percent;
322         }
323
324         return $multipliers;
325     }
326
327     /**
328      * Get the available query operators as a regex escaped list.
329      */
330     protected function getRegexEscapedOperators(): string
331     {
332         $escapedOperators = [];
333         foreach ($this->queryOperators as $operator) {
334             $escapedOperators[] = preg_quote($operator);
335         }
336
337         return implode('|', $escapedOperators);
338     }
339
340     /**
341      * Apply a tag search term onto a entity query.
342      */
343     protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
344     {
345         preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit);
346         $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
347             $tagName = $tagSplit[1];
348             $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
349             $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
350             $validOperator = in_array($tagOperator, $this->queryOperators);
351             if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
352                 if (!empty($tagName)) {
353                     $query->where('name', '=', $tagName);
354                 }
355                 if (is_numeric($tagValue) && $tagOperator !== 'like') {
356                     // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
357                     // search the value as a string which prevents being able to do number-based operations
358                     // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
359                     $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
360                     $query->whereRaw("value ${tagOperator} ${tagValue}");
361                 } else {
362                     $query->where('value', $tagOperator, $tagValue);
363                 }
364             } else {
365                 $query->where('name', '=', $tagName);
366             }
367         });
368
369         return $query;
370     }
371
372     /**
373      * Custom entity search filters.
374      */
375     protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input): void
376     {
377         try {
378             $date = date_create($input);
379             $query->where('updated_at', '>=', $date);
380         } catch (\Exception $e) {
381         }
382     }
383
384     protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input): void
385     {
386         try {
387             $date = date_create($input);
388             $query->where('updated_at', '<', $date);
389         } catch (\Exception $e) {
390         }
391     }
392
393     protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input): void
394     {
395         try {
396             $date = date_create($input);
397             $query->where('created_at', '>=', $date);
398         } catch (\Exception $e) {
399         }
400     }
401
402     protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
403     {
404         try {
405             $date = date_create($input);
406             $query->where('created_at', '<', $date);
407         } catch (\Exception $e) {
408         }
409     }
410
411     protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
412     {
413         $userSlug = $input === 'me' ? user()->slug : trim($input);
414         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
415         if ($user) {
416             $query->where('created_by', '=', $user->id);
417         }
418     }
419
420     protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
421     {
422         $userSlug = $input === 'me' ? user()->slug : trim($input);
423         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
424         if ($user) {
425             $query->where('updated_by', '=', $user->id);
426         }
427     }
428
429     protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
430     {
431         $userSlug = $input === 'me' ? user()->slug : trim($input);
432         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
433         if ($user) {
434             $query->where('owned_by', '=', $user->id);
435         }
436     }
437
438     protected function filterInName(EloquentBuilder $query, Entity $model, $input)
439     {
440         $query->where('name', 'like', '%' . $input . '%');
441     }
442
443     protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
444     {
445         $this->filterInName($query, $model, $input);
446     }
447
448     protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
449     {
450         $query->where($model->textField, 'like', '%' . $input . '%');
451     }
452
453     protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
454     {
455         $query->where('restricted', '=', true);
456     }
457
458     protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
459     {
460         $query->whereHas('views', function ($query) {
461             $query->where('user_id', '=', user()->id);
462         });
463     }
464
465     protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
466     {
467         $query->whereDoesntHave('views', function ($query) {
468             $query->where('user_id', '=', user()->id);
469         });
470     }
471
472     protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
473     {
474         $functionName = Str::camel('sort_by_' . $input);
475         if (method_exists($this, $functionName)) {
476             $this->$functionName($query, $model);
477         }
478     }
479
480     /**
481      * Sorting filter options.
482      */
483     protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
484     {
485         $commentsTable = DB::getTablePrefix() . 'comments';
486         $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
487         $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');
488
489         $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');
490     }
491 }