3 namespace BookStack\Search;
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 Illuminate\Database\Connection;
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;
23 protected EntityProvider $entityProvider;
24 protected PermissionApplicator $permissions;
27 * Acceptable operators to be used in a query.
31 protected array $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
34 * Retain a cache of score adjusted terms for specific search options.
35 * From PHP>=8 this can be made into a WeakMap instead.
37 * @var SplObjectStorage
39 protected $termAdjustmentCache;
41 public function __construct(EntityProvider $entityProvider, PermissionApplicator $permissions)
43 $this->entityProvider = $entityProvider;
44 $this->permissions = $permissions;
45 $this->termAdjustmentCache = new SplObjectStorage();
49 * Search all entities in the system.
50 * The provided count is for each entity to search,
51 * Total returned could be larger and not guaranteed.
53 * @return array{total: int, count: int, has_more: bool, results: Collection<Entity>}
55 public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20): array
57 $entityTypes = array_keys($this->entityProvider->all());
58 $entityTypesToSearch = $entityTypes;
60 if ($entityType !== 'all') {
61 $entityTypesToSearch = $entityType;
62 } elseif (isset($searchOpts->filters['type'])) {
63 $entityTypesToSearch = explode('|', $searchOpts->filters['type']);
70 foreach ($entityTypesToSearch as $entityType) {
71 if (!in_array($entityType, $entityTypes)) {
75 $entityModelInstance = $this->entityProvider->get($entityType);
76 $searchQuery = $this->buildQuery($searchOpts, $entityModelInstance);
77 $entityTotal = $searchQuery->count();
78 $searchResults = $this->getPageOfDataFromQuery($searchQuery, $entityModelInstance, $page, $count);
80 if ($entityTotal > ($page * $count)) {
84 $total += $entityTotal;
85 $results = $results->merge($searchResults);
90 'count' => count($results),
91 'has_more' => $hasMore,
92 'results' => $results->sortByDesc('score')->values(),
97 * Search a book for entities.
99 public function searchBook(int $bookId, string $searchString): Collection
101 $opts = SearchOptions::fromString($searchString);
102 $entityTypes = ['page', 'chapter'];
103 $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
105 $results = collect();
106 foreach ($entityTypesToSearch as $entityType) {
107 if (!in_array($entityType, $entityTypes)) {
111 $entityModelInstance = $this->entityProvider->get($entityType);
112 $search = $this->buildQuery($opts, $entityModelInstance)->where('book_id', '=', $bookId)->take(20)->get();
113 $results = $results->merge($search);
116 return $results->sortByDesc('score')->take(20);
120 * Search a chapter for entities.
122 public function searchChapter(int $chapterId, string $searchString): Collection
124 $opts = SearchOptions::fromString($searchString);
125 $entityModelInstance = $this->entityProvider->get('page');
126 $pages = $this->buildQuery($opts, $entityModelInstance)->where('chapter_id', '=', $chapterId)->take(20)->get();
128 return $pages->sortByDesc('score');
132 * Get a page of result data from the given query based on the provided page parameters.
134 protected function getPageOfDataFromQuery(EloquentBuilder $query, Entity $entityModelInstance, int $page = 1, int $count = 20): EloquentCollection
136 $relations = ['tags'];
138 if ($entityModelInstance instanceof BookChild) {
139 $relations['book'] = function (BelongsTo $query) {
140 $query->scopes('visible');
144 if ($entityModelInstance instanceof Page) {
145 $relations['chapter'] = function (BelongsTo $query) {
146 $query->scopes('visible');
150 return $query->clone()
151 ->with(array_filter($relations))
152 ->skip(($page - 1) * $count)
158 * Create a search query for an entity.
160 protected function buildQuery(SearchOptions $searchOpts, Entity $entityModelInstance): EloquentBuilder
162 $entityQuery = $entityModelInstance->newQuery()->scopes('visible');
164 if ($entityModelInstance instanceof Page) {
165 $entityQuery->select(array_merge($entityModelInstance::$listAttributes, ['owned_by']));
167 $entityQuery->select(['*']);
170 // Handle normal search terms
171 $this->applyTermSearch($entityQuery, $searchOpts, $entityModelInstance);
173 // Handle exact term matching
174 foreach ($searchOpts->exacts as $inputTerm) {
175 $entityQuery->where(function (EloquentBuilder $query) use ($inputTerm, $entityModelInstance) {
176 $query->where('name', 'like', '%' . $inputTerm . '%')
177 ->orWhere($entityModelInstance->textField, 'like', '%' . $inputTerm . '%');
181 // Handle tag searches
182 foreach ($searchOpts->tags as $inputTerm) {
183 $this->applyTagSearch($entityQuery, $inputTerm);
187 foreach ($searchOpts->filters as $filterTerm => $filterValue) {
188 $functionName = Str::camel('filter_' . $filterTerm);
189 if (method_exists($this, $functionName)) {
190 $this->$functionName($entityQuery, $entityModelInstance, $filterValue);
198 * For the given search query, apply the queries for handling the regular search terms.
200 protected function applyTermSearch(EloquentBuilder $entityQuery, SearchOptions $options, Entity $entity): void
202 $terms = $options->searches;
203 if (count($terms) === 0) {
207 $scoredTerms = $this->getTermAdjustments($options);
208 $scoreSelect = $this->selectForScoredTerms($scoredTerms);
210 $subQuery = DB::table('search_terms')->select([
213 DB::raw($scoreSelect['statement']),
216 $subQuery->addBinding($scoreSelect['bindings'], 'select');
218 $subQuery->where('entity_type', '=', $entity->getMorphClass());
219 $subQuery->where(function (Builder $query) use ($terms) {
220 foreach ($terms as $inputTerm) {
221 $query->orWhere('term', 'like', $inputTerm . '%');
224 $subQuery->groupBy('entity_type', 'entity_id');
226 $entityQuery->joinSub($subQuery, 's', 'id', '=', 's.entity_id');
227 $entityQuery->addSelect('s.score');
228 $entityQuery->orderBy('score', 'desc');
232 * Create a select statement, with prepared bindings, for the given
233 * set of scored search terms.
235 * @param array<string, float> $scoredTerms
237 * @return array{statement: string, bindings: string[]}
239 protected function selectForScoredTerms(array $scoredTerms): array
241 // Within this we walk backwards to create the chain of 'if' statements
242 // so that each previous statement is used in the 'else' condition of
243 // the next (earlier) to be built. We start at '0' to have no score
244 // on no match (Should never actually get to this case).
247 foreach ($scoredTerms as $term => $score) {
248 $ifChain = 'IF(term like ?, score * ' . (float) $score . ', ' . $ifChain . ')';
249 $bindings[] = $term . '%';
253 'statement' => 'SUM(' . $ifChain . ') as score',
254 'bindings' => array_reverse($bindings),
259 * For the terms in the given search options, query their popularity across all
260 * search terms then provide that back as score adjustment multiplier applicable
261 * for their rarity. Returns an array of float multipliers, keyed by term.
263 * @return array<string, float>
265 protected function getTermAdjustments(SearchOptions $options): array
267 if (isset($this->termAdjustmentCache[$options])) {
268 return $this->termAdjustmentCache[$options];
271 $termQuery = SearchTerm::query()->toBase();
272 $whenStatements = [];
275 foreach ($options->searches as $term) {
276 $whenStatements[] = 'WHEN term LIKE ? THEN ?';
277 $whenBindings[] = $term . '%';
278 $whenBindings[] = $term;
280 $termQuery->orWhere('term', 'like', $term . '%');
283 $case = 'CASE ' . implode(' ', $whenStatements) . ' END';
284 $termQuery->selectRaw($case . ' as term', $whenBindings);
285 $termQuery->selectRaw('COUNT(*) as count');
286 $termQuery->groupByRaw($case, $whenBindings);
288 $termCounts = $termQuery->pluck('count', 'term')->toArray();
289 $adjusted = $this->rawTermCountsToAdjustments($termCounts);
291 $this->termAdjustmentCache[$options] = $adjusted;
293 return $this->termAdjustmentCache[$options];
297 * Convert counts of terms into a relative-count normalised multiplier.
299 * @param array<string, int> $termCounts
301 * @return array<string, int>
303 protected function rawTermCountsToAdjustments(array $termCounts): array
305 if (empty($termCounts)) {
310 $max = max(array_values($termCounts));
312 foreach ($termCounts as $term => $count) {
313 $percent = round($count / $max, 5);
314 $multipliers[$term] = 1.3 - $percent;
321 * Get the available query operators as a regex escaped list.
323 protected function getRegexEscapedOperators(): string
325 $escapedOperators = [];
326 foreach ($this->queryOperators as $operator) {
327 $escapedOperators[] = preg_quote($operator);
330 return implode('|', $escapedOperators);
334 * Apply a tag search term onto a entity query.
336 protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
338 preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit);
339 $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
340 $tagName = $tagSplit[1];
341 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
342 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
343 $validOperator = in_array($tagOperator, $this->queryOperators);
344 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
345 if (!empty($tagName)) {
346 $query->where('name', '=', $tagName);
348 if (is_numeric($tagValue) && $tagOperator !== 'like') {
349 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
350 // search the value as a string which prevents being able to do number-based operations
351 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
352 /** @var Connection $connection */
353 $connection = $query->getConnection();
354 $tagValue = (float) trim($connection->getPdo()->quote($tagValue), "'");
355 $query->whereRaw("value {$tagOperator} {$tagValue}");
357 $query->where('value', $tagOperator, $tagValue);
360 $query->where('name', '=', $tagName);
368 * Custom entity search filters.
370 protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input): void
373 $date = date_create($input);
374 $query->where('updated_at', '>=', $date);
375 } catch (\Exception $e) {
379 protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input): void
382 $date = date_create($input);
383 $query->where('updated_at', '<', $date);
384 } catch (\Exception $e) {
388 protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input): void
391 $date = date_create($input);
392 $query->where('created_at', '>=', $date);
393 } catch (\Exception $e) {
397 protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
400 $date = date_create($input);
401 $query->where('created_at', '<', $date);
402 } catch (\Exception $e) {
406 protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
408 $userSlug = $input === 'me' ? user()->slug : trim($input);
409 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
411 $query->where('created_by', '=', $user->id);
415 protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
417 $userSlug = $input === 'me' ? user()->slug : trim($input);
418 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
420 $query->where('updated_by', '=', $user->id);
424 protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
426 $userSlug = $input === 'me' ? user()->slug : trim($input);
427 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
429 $query->where('owned_by', '=', $user->id);
433 protected function filterInName(EloquentBuilder $query, Entity $model, $input)
435 $query->where('name', 'like', '%' . $input . '%');
438 protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
440 $this->filterInName($query, $model, $input);
443 protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
445 $query->where($model->textField, 'like', '%' . $input . '%');
448 protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
450 $query->whereHas('permissions');
453 protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
455 $query->whereHas('views', function ($query) {
456 $query->where('user_id', '=', user()->id);
460 protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
462 $query->whereDoesntHave('views', function ($query) {
463 $query->where('user_id', '=', user()->id);
467 protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
469 $functionName = Str::camel('sort_by_' . $input);
470 if (method_exists($this, $functionName)) {
471 $this->$functionName($query, $model);
476 * Sorting filter options.
478 protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
480 $commentsTable = DB::getTablePrefix() . 'comments';
481 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
482 $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 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');