]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/SearchRunner.php
Applied styleci fixes and pluck improvement as per larastan
[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      *
220      * @return array{statement: string, bindings: string[]}
221      */
222     protected function selectForScoredTerms(array $scoredTerms): array
223     {
224         // Within this we walk backwards to create the chain of 'if' statements
225         // so that each previous statement is used in the 'else' condition of
226         // the next (earlier) to be built. We start at '0' to have no score
227         // on no match (Should never actually get to this case).
228         $ifChain = '0';
229         $bindings = [];
230         foreach ($scoredTerms as $term => $score) {
231             $ifChain = 'IF(term like ?, score * ' . (float) $score . ', ' . $ifChain . ')';
232             $bindings[] = $term . '%';
233         }
234
235         return [
236             'statement' => 'SUM(' . $ifChain . ') as score',
237             'bindings'  => array_reverse($bindings),
238         ];
239     }
240
241     protected function getTermAdjustments(SearchOptions $options): array
242     {
243         if (isset($this->termAdjustmentCache[$options])) {
244             return $this->termAdjustmentCache[$options];
245         }
246
247         $termQuery = SearchTerm::query()->toBase();
248         $whenStatements = [];
249         $whenBindings = [];
250
251         foreach ($options->searches as $term) {
252             $whenStatements[] = 'WHEN term LIKE ? THEN ?';
253             $whenBindings[] = $term . '%';
254             $whenBindings[] = $term;
255
256             $termQuery->orWhere('term', 'like', $term . '%');
257         }
258
259         $case = 'CASE ' . implode(' ', $whenStatements) . ' END';
260         $termQuery->selectRaw($case . ' as term', $whenBindings);
261         $termQuery->selectRaw('COUNT(*) as count');
262         $termQuery->groupByRaw($case, $whenBindings);
263
264         $termCounts = $termQuery->pluck('count', 'term')->toArray();
265         $adjusted = $this->rawTermCountsToAdjustments($termCounts);
266
267         $this->termAdjustmentCache[$options] = $adjusted;
268
269         return $this->termAdjustmentCache[$options];
270     }
271
272     /**
273      * Convert counts of terms into a relative-count normalised multiplier.
274      *
275      * @param array<string, int> $termCounts
276      *
277      * @return array<string, int>
278      */
279     protected function rawTermCountsToAdjustments(array $termCounts): array
280     {
281         if (empty($termCounts)) {
282             return [];
283         }
284         
285         $multipliers = [];
286         $max = max(array_values($termCounts));
287
288         foreach ($termCounts as $term => $count) {
289             $percent = round($count / $max, 5);
290             $multipliers[$term] = 1.3 - $percent;
291         }
292
293         return $multipliers;
294     }
295
296     /**
297      * Get the available query operators as a regex escaped list.
298      */
299     protected function getRegexEscapedOperators(): string
300     {
301         $escapedOperators = [];
302         foreach ($this->queryOperators as $operator) {
303             $escapedOperators[] = preg_quote($operator);
304         }
305
306         return implode('|', $escapedOperators);
307     }
308
309     /**
310      * Apply a tag search term onto a entity query.
311      */
312     protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
313     {
314         preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit);
315         $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
316             $tagName = $tagSplit[1];
317             $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
318             $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
319             $validOperator = in_array($tagOperator, $this->queryOperators);
320             if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
321                 if (!empty($tagName)) {
322                     $query->where('name', '=', $tagName);
323                 }
324                 if (is_numeric($tagValue) && $tagOperator !== 'like') {
325                     // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
326                     // search the value as a string which prevents being able to do number-based operations
327                     // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
328                     $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
329                     $query->whereRaw("value ${tagOperator} ${tagValue}");
330                 } else {
331                     $query->where('value', $tagOperator, $tagValue);
332                 }
333             } else {
334                 $query->where('name', '=', $tagName);
335             }
336         });
337
338         return $query;
339     }
340
341     /**
342      * Custom entity search filters.
343      */
344     protected function filterUpdatedAfter(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
353     protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input): void
354     {
355         try {
356             $date = date_create($input);
357             $query->where('updated_at', '<', $date);
358         } catch (\Exception $e) {
359         }
360     }
361
362     protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input): void
363     {
364         try {
365             $date = date_create($input);
366             $query->where('created_at', '>=', $date);
367         } catch (\Exception $e) {
368         }
369     }
370
371     protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
372     {
373         try {
374             $date = date_create($input);
375             $query->where('created_at', '<', $date);
376         } catch (\Exception $e) {
377         }
378     }
379
380     protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
381     {
382         $userSlug = $input === 'me' ? user()->slug : trim($input);
383         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
384         if ($user) {
385             $query->where('created_by', '=', $user->id);
386         }
387     }
388
389     protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
390     {
391         $userSlug = $input === 'me' ? user()->slug : trim($input);
392         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
393         if ($user) {
394             $query->where('updated_by', '=', $user->id);
395         }
396     }
397
398     protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
399     {
400         $userSlug = $input === 'me' ? user()->slug : trim($input);
401         $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
402         if ($user) {
403             $query->where('owned_by', '=', $user->id);
404         }
405     }
406
407     protected function filterInName(EloquentBuilder $query, Entity $model, $input)
408     {
409         $query->where('name', 'like', '%' . $input . '%');
410     }
411
412     protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
413     {
414         $this->filterInName($query, $model, $input);
415     }
416
417     protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
418     {
419         $query->where($model->textField, 'like', '%' . $input . '%');
420     }
421
422     protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
423     {
424         $query->where('restricted', '=', true);
425     }
426
427     protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
428     {
429         $query->whereHas('views', function ($query) {
430             $query->where('user_id', '=', user()->id);
431         });
432     }
433
434     protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
435     {
436         $query->whereDoesntHave('views', function ($query) {
437             $query->where('user_id', '=', user()->id);
438         });
439     }
440
441     protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
442     {
443         $functionName = Str::camel('sort_by_' . $input);
444         if (method_exists($this, $functionName)) {
445             $this->$functionName($query, $model);
446         }
447     }
448
449     /**
450      * Sorting filter options.
451      */
452     protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
453     {
454         $commentsTable = DB::getTablePrefix() . 'comments';
455         $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
456         $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');
457
458         $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');
459     }
460 }