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