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