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