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