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