]> BookStack Code Mirror - bookstack/blob - app/Search/SearchRunner.php
Played around with a new app structure
[bookstack] / app / Search / SearchRunner.php
1 <?php
2
3 namespace BookStack\Search;
4
5 use BookStack\Entities\EntityProvider;
6 use BookStack\Entities\Models\BookChild;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Entities\Models\Page;
9 use BookStack\Permissions\PermissionApplicator;
10 use BookStack\Users\Models\User;
11 use Illuminate\Database\Connection;
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     protected EntityProvider $entityProvider;
24     protected PermissionApplicator $permissions;
25
26     /**
27      * Acceptable operators to be used in a query.
28      *
29      * @var string[]
30      */
31     protected array $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
32
33     /**
34      * Retain a cache of score adjusted terms for specific search options.
35      * From PHP>=8 this can be made into a WeakMap instead.
36      *
37      * @var SplObjectStorage
38      */
39     protected $termAdjustmentCache;
40
41     public function __construct(EntityProvider $entityProvider, PermissionApplicator $permissions)
42     {
43         $this->entityProvider = $entityProvider;
44         $this->permissions = $permissions;
45         $this->termAdjustmentCache = new SplObjectStorage();
46     }
47
48     /**
49      * Search all entities in the system.
50      * The provided count is for each entity to search,
51      * Total returned could be larger and not guaranteed.
52      *
53      * @return array{total: int, count: int, has_more: bool, results: Collection<Entity>}
54      */
55     public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20): array
56     {
57         $entityTypes = array_keys($this->entityProvider->all());
58         $entityTypesToSearch = $entityTypes;
59
60         if ($entityType !== 'all') {
61             $entityTypesToSearch = $entityType;
62         } elseif (isset($searchOpts->filters['type'])) {
63             $entityTypesToSearch = explode('|', $searchOpts->filters['type']);
64         }
65
66         $results = collect();
67         $total = 0;
68         $hasMore = false;
69
70         foreach ($entityTypesToSearch as $entityType) {
71             if (!in_array($entityType, $entityTypes)) {
72                 continue;
73             }
74
75             $entityModelInstance = $this->entityProvider->get($entityType);
76             $searchQuery = $this->buildQuery($searchOpts, $entityModelInstance);
77             $entityTotal = $searchQuery->count();
78             $searchResults = $this->getPageOfDataFromQuery($searchQuery, $entityModelInstance, $page, $count);
79
80             if ($entityTotal > ($page * $count)) {
81                 $hasMore = true;
82             }
83
84             $total += $entityTotal;
85             $results = $results->merge($searchResults);
86         }
87
88         return [
89             'total'    => $total,
90             'count'    => count($results),
91             'has_more' => $hasMore,
92             'results'  => $results->sortByDesc('score')->values(),
93         ];
94     }
95
96     /**
97      * Search a book for entities.
98      */
99     public function searchBook(int $bookId, string $searchString): Collection
100     {
101         $opts = SearchOptions::fromString($searchString);
102         $entityTypes = ['page', 'chapter'];
103         $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
104
105         $results = collect();
106         foreach ($entityTypesToSearch as $entityType) {
107             if (!in_array($entityType, $entityTypes)) {
108                 continue;
109             }
110
111             $entityModelInstance = $this->entityProvider->get($entityType);
112             $search = $this->buildQuery($opts, $entityModelInstance)->where('book_id', '=', $bookId)->take(20)->get();
113             $results = $results->merge($search);
114         }
115
116         return $results->sortByDesc('score')->take(20);
117     }
118
119     /**
120      * Search a chapter for entities.
121      */
122     public function searchChapter(int $chapterId, string $searchString): Collection
123     {
124         $opts = SearchOptions::fromString($searchString);
125         $entityModelInstance = $this->entityProvider->get('page');
126         $pages = $this->buildQuery($opts, $entityModelInstance)->where('chapter_id', '=', $chapterId)->take(20)->get();
127
128         return $pages->sortByDesc('score');
129     }
130
131     /**
132      * Get a page of result data from the given query based on the provided page parameters.
133      */
134     protected function getPageOfDataFromQuery(EloquentBuilder $query, Entity $entityModelInstance, int $page = 1, int $count = 20): EloquentCollection
135     {
136         $relations = ['tags'];
137
138         if ($entityModelInstance instanceof BookChild) {
139             $relations['book'] = function (BelongsTo $query) {
140                 $query->scopes('visible');
141             };
142         }
143
144         if ($entityModelInstance instanceof Page) {
145             $relations['chapter'] = function (BelongsTo $query) {
146                 $query->scopes('visible');
147             };
148         }
149
150         return $query->clone()
151             ->with(array_filter($relations))
152             ->skip(($page - 1) * $count)
153             ->take($count)
154             ->get();
155     }
156
157     /**
158      * Create a search query for an entity.
159      */
160     protected function buildQuery(SearchOptions $searchOpts, Entity $entityModelInstance): EloquentBuilder
161     {
162         $entityQuery = $entityModelInstance->newQuery()->scopes('visible');
163
164         if ($entityModelInstance instanceof Page) {
165             $entityQuery->select(array_merge($entityModelInstance::$listAttributes, ['owned_by']));
166         } else {
167             $entityQuery->select(['*']);
168         }
169
170         // Handle normal search terms
171         $this->applyTermSearch($entityQuery, $searchOpts, $entityModelInstance);
172
173         // Handle exact term matching
174         foreach ($searchOpts->exacts as $inputTerm) {
175             $entityQuery->where(function (EloquentBuilder $query) use ($inputTerm, $entityModelInstance) {
176                 $inputTerm = str_replace('\\', '\\\\', $inputTerm);
177                 $query->where('name', 'like', '%' . $inputTerm . '%')
178                     ->orWhere($entityModelInstance->textField, 'like', '%' . $inputTerm . '%');
179             });
180         }
181
182         // Handle tag searches
183         foreach ($searchOpts->tags as $inputTerm) {
184             $this->applyTagSearch($entityQuery, $inputTerm);
185         }
186
187         // Handle filters
188         foreach ($searchOpts->filters as $filterTerm => $filterValue) {
189             $functionName = Str::camel('filter_' . $filterTerm);
190             if (method_exists($this, $functionName)) {
191                 $this->$functionName($entityQuery, $entityModelInstance, $filterValue);
192             }
193         }
194
195         return $entityQuery;
196     }
197
198     /**
199      * For the given search query, apply the queries for handling the regular search terms.
200      */
201     protected function applyTermSearch(EloquentBuilder $entityQuery, SearchOptions $options, Entity $entity): void
202     {
203         $terms = $options->searches;
204         if (count($terms) === 0) {
205             return;
206         }
207
208         $scoredTerms = $this->getTermAdjustments($options);
209         $scoreSelect = $this->selectForScoredTerms($scoredTerms);
210
211         $subQuery = DB::table('search_terms')->select([
212             'entity_id',
213             'entity_type',
214             DB::raw($scoreSelect['statement']),
215         ]);
216
217         $subQuery->addBinding($scoreSelect['bindings'], 'select');
218
219         $subQuery->where('entity_type', '=', $entity->getMorphClass());
220         $subQuery->where(function (Builder $query) use ($terms) {
221             foreach ($terms as $inputTerm) {
222                 $inputTerm = str_replace('\\', '\\\\', $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                     if ($tagOperator === 'like') {
360                         $tagValue = str_replace('\\', '\\\\', $tagValue);
361                     }
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->whereHas('permissions');
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 }