]> BookStack Code Mirror - bookstack/blob - app/Search/SearchRunner.php
Added method for using enity ownership in relation queries
[bookstack] / app / Search / SearchRunner.php
1 <?php
2
3 namespace BookStack\Search;
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 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                 $query->where('name', 'like', '%' . $inputTerm . '%')
177                     ->orWhere($entityModelInstance->textField, 'like', '%' . $inputTerm . '%');
178             });
179         }
180
181         // Handle tag searches
182         foreach ($searchOpts->tags as $inputTerm) {
183             $this->applyTagSearch($entityQuery, $inputTerm);
184         }
185
186         // Handle filters
187         foreach ($searchOpts->filters as $filterTerm => $filterValue) {
188             $functionName = Str::camel('filter_' . $filterTerm);
189             if (method_exists($this, $functionName)) {
190                 $this->$functionName($entityQuery, $entityModelInstance, $filterValue);
191             }
192         }
193
194         return $entityQuery;
195     }
196
197     /**
198      * For the given search query, apply the queries for handling the regular search terms.
199      */
200     protected function applyTermSearch(EloquentBuilder $entityQuery, SearchOptions $options, Entity $entity): void
201     {
202         $terms = $options->searches;
203         if (count($terms) === 0) {
204             return;
205         }
206
207         $scoredTerms = $this->getTermAdjustments($options);
208         $scoreSelect = $this->selectForScoredTerms($scoredTerms);
209
210         $subQuery = DB::table('search_terms')->select([
211             'entity_id',
212             'entity_type',
213             DB::raw($scoreSelect['statement']),
214         ]);
215
216         $subQuery->addBinding($scoreSelect['bindings'], 'select');
217
218         $subQuery->where('entity_type', '=', $entity->getMorphClass());
219         $subQuery->where(function (Builder $query) use ($terms) {
220             foreach ($terms as $inputTerm) {
221                 $query->orWhere('term', 'like', $inputTerm . '%');
222             }
223         });
224         $subQuery->groupBy('entity_type', 'entity_id');
225
226         $entityQuery->joinSub($subQuery, 's', 'id', '=', 's.entity_id');
227         $entityQuery->addSelect('s.score');
228         $entityQuery->orderBy('score', 'desc');
229     }
230
231     /**
232      * Create a select statement, with prepared bindings, for the given
233      * set of scored search terms.
234      *
235      * @param array<string, float> $scoredTerms
236      *
237      * @return array{statement: string, bindings: string[]}
238      */
239     protected function selectForScoredTerms(array $scoredTerms): array
240     {
241         // Within this we walk backwards to create the chain of 'if' statements
242         // so that each previous statement is used in the 'else' condition of
243         // the next (earlier) to be built. We start at '0' to have no score
244         // on no match (Should never actually get to this case).
245         $ifChain = '0';
246         $bindings = [];
247         foreach ($scoredTerms as $term => $score) {
248             $ifChain = 'IF(term like ?, score * ' . (float) $score . ', ' . $ifChain . ')';
249             $bindings[] = $term . '%';
250         }
251
252         return [
253             'statement' => 'SUM(' . $ifChain . ') as score',
254             'bindings'  => array_reverse($bindings),
255         ];
256     }
257
258     /**
259      * For the terms in the given search options, query their popularity across all
260      * search terms then provide that back as score adjustment multiplier applicable
261      * for their rarity. Returns an array of float multipliers, keyed by term.
262      *
263      * @return array<string, float>
264      */
265     protected function getTermAdjustments(SearchOptions $options): array
266     {
267         if (isset($this->termAdjustmentCache[$options])) {
268             return $this->termAdjustmentCache[$options];
269         }
270
271         $termQuery = SearchTerm::query()->toBase();
272         $whenStatements = [];
273         $whenBindings = [];
274
275         foreach ($options->searches as $term) {
276             $whenStatements[] = 'WHEN term LIKE ? THEN ?';
277             $whenBindings[] = $term . '%';
278             $whenBindings[] = $term;
279
280             $termQuery->orWhere('term', 'like', $term . '%');
281         }
282
283         $case = 'CASE ' . implode(' ', $whenStatements) . ' END';
284         $termQuery->selectRaw($case . ' as term', $whenBindings);
285         $termQuery->selectRaw('COUNT(*) as count');
286         $termQuery->groupByRaw($case, $whenBindings);
287
288         $termCounts = $termQuery->pluck('count', 'term')->toArray();
289         $adjusted = $this->rawTermCountsToAdjustments($termCounts);
290
291         $this->termAdjustmentCache[$options] = $adjusted;
292
293         return $this->termAdjustmentCache[$options];
294     }
295
296     /**
297      * Convert counts of terms into a relative-count normalised multiplier.
298      *
299      * @param array<string, int> $termCounts
300      *
301      * @return array<string, int>
302      */
303     protected function rawTermCountsToAdjustments(array $termCounts): array
304     {
305         if (empty($termCounts)) {
306             return [];
307         }
308
309         $multipliers = [];
310         $max = max(array_values($termCounts));
311
312         foreach ($termCounts as $term => $count) {
313             $percent = round($count / $max, 5);
314             $multipliers[$term] = 1.3 - $percent;
315         }
316
317         return $multipliers;
318     }
319
320     /**
321      * Get the available query operators as a regex escaped list.
322      */
323     protected function getRegexEscapedOperators(): string
324     {
325         $escapedOperators = [];
326         foreach ($this->queryOperators as $operator) {
327             $escapedOperators[] = preg_quote($operator);
328         }
329
330         return implode('|', $escapedOperators);
331     }
332
333     /**
334      * Apply a tag search term onto a entity query.
335      */
336     protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
337     {
338         preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit);
339         $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
340             $tagName = $tagSplit[1];
341             $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
342             $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
343             $validOperator = in_array($tagOperator, $this->queryOperators);
344             if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
345                 if (!empty($tagName)) {
346                     $query->where('name', '=', $tagName);
347                 }
348                 if (is_numeric($tagValue) && $tagOperator !== 'like') {
349                     // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
350                     // search the value as a string which prevents being able to do number-based operations
351                     // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
352                     /** @var Connection $connection */
353                     $connection = $query->getConnection();
354                     $tagValue = (float) trim($connection->getPdo()->quote($tagValue), "'");
355                     $query->whereRaw("value {$tagOperator} {$tagValue}");
356                 } else {
357                     $query->where('value', $tagOperator, $tagValue);
358                 }
359             } else {
360                 $query->where('name', '=', $tagName);
361             }
362         });
363
364         return $query;
365     }
366
367     /**
368      * Custom entity search filters.
369      */
370     protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input): void
371     {
372         try {
373             $date = date_create($input);
374             $query->where('updated_at', '>=', $date);
375         } catch (\Exception $e) {
376         }
377     }
378
379     protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input): void
380     {
381         try {
382             $date = date_create($input);
383             $query->where('updated_at', '<', $date);
384         } catch (\Exception $e) {
385         }
386     }
387
388     protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input): void
389     {
390         try {
391             $date = date_create($input);
392             $query->where('created_at', '>=', $date);
393         } catch (\Exception $e) {
394         }
395     }
396
397     protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
398     {
399         try {
400             $date = date_create($input);
401             $query->where('created_at', '<', $date);
402         } catch (\Exception $e) {
403         }
404     }
405
406     protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
407     {
408         $userSlug = $input === 'me' ? user()->slug : trim($input);
409         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
410         if ($user) {
411             $query->where('created_by', '=', $user->id);
412         }
413     }
414
415     protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
416     {
417         $userSlug = $input === 'me' ? user()->slug : trim($input);
418         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
419         if ($user) {
420             $query->where('updated_by', '=', $user->id);
421         }
422     }
423
424     protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
425     {
426         $userSlug = $input === 'me' ? user()->slug : trim($input);
427         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
428         if ($user) {
429             $query->where('owned_by', '=', $user->id);
430         }
431     }
432
433     protected function filterInName(EloquentBuilder $query, Entity $model, $input)
434     {
435         $query->where('name', 'like', '%' . $input . '%');
436     }
437
438     protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
439     {
440         $this->filterInName($query, $model, $input);
441     }
442
443     protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
444     {
445         $query->where($model->textField, 'like', '%' . $input . '%');
446     }
447
448     protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
449     {
450         $query->whereHas('permissions');
451     }
452
453     protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
454     {
455         $query->whereHas('views', function ($query) {
456             $query->where('user_id', '=', user()->id);
457         });
458     }
459
460     protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
461     {
462         $query->whereDoesntHave('views', function ($query) {
463             $query->where('user_id', '=', user()->id);
464         });
465     }
466
467     protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
468     {
469         $functionName = Str::camel('sort_by_' . $input);
470         if (method_exists($this, $functionName)) {
471             $this->$functionName($query, $model);
472         }
473     }
474
475     /**
476      * Sorting filter options.
477      */
478     protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
479     {
480         $commentsTable = DB::getTablePrefix() . 'comments';
481         $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
482         $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');
483
484         $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');
485     }
486 }