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