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