3 namespace BookStack\Search;
5 use BookStack\Entities\EntityProvider;
6 use BookStack\Entities\Models\BookChild;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Entities\Models\Page;
9 use BookStack\Permissions\PermissionApplicator;
10 use BookStack\Users\Models\User;
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 $inputTerm = str_replace('\\', '\\\\', $inputTerm);
177 $query->where('name', 'like', '%' . $inputTerm . '%')
178 ->orWhere($entityModelInstance->textField, 'like', '%' . $inputTerm . '%');
182 // Handle tag searches
183 foreach ($searchOpts->tags as $inputTerm) {
184 $this->applyTagSearch($entityQuery, $inputTerm);
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);
199 * For the given search query, apply the queries for handling the regular search terms.
201 protected function applyTermSearch(EloquentBuilder $entityQuery, SearchOptions $options, Entity $entity): void
203 $terms = $options->searches;
204 if (count($terms) === 0) {
208 $scoredTerms = $this->getTermAdjustments($options);
209 $scoreSelect = $this->selectForScoredTerms($scoredTerms);
211 $subQuery = DB::table('search_terms')->select([
214 DB::raw($scoreSelect['statement']),
217 $subQuery->addBinding($scoreSelect['bindings'], 'select');
219 $subQuery->where('entity_type', '=', $entity->getMorphClass());
220 $subQuery->where(function (Builder $query) use ($terms) {
221 foreach ($terms as $inputTerm) {
222 $inputTerm = str_replace('\\', '\\\\', $inputTerm);
223 $query->orWhere('term', 'like', $inputTerm . '%');
226 $subQuery->groupBy('entity_type', 'entity_id');
228 $entityQuery->joinSub($subQuery, 's', 'id', '=', 'entity_id');
229 $entityQuery->addSelect('s.score');
230 $entityQuery->orderBy('score', 'desc');
234 * Create a select statement, with prepared bindings, for the given
235 * set of scored search terms.
237 * @param array<string, float> $scoredTerms
239 * @return array{statement: string, bindings: string[]}
241 protected function selectForScoredTerms(array $scoredTerms): array
243 // Within this we walk backwards to create the chain of 'if' statements
244 // so that each previous statement is used in the 'else' condition of
245 // the next (earlier) to be built. We start at '0' to have no score
246 // on no match (Should never actually get to this case).
249 foreach ($scoredTerms as $term => $score) {
250 $ifChain = 'IF(term like ?, score * ' . (float) $score . ', ' . $ifChain . ')';
251 $bindings[] = $term . '%';
255 'statement' => 'SUM(' . $ifChain . ') as score',
256 'bindings' => array_reverse($bindings),
261 * For the terms in the given search options, query their popularity across all
262 * search terms then provide that back as score adjustment multiplier applicable
263 * for their rarity. Returns an array of float multipliers, keyed by term.
265 * @return array<string, float>
267 protected function getTermAdjustments(SearchOptions $options): array
269 if (isset($this->termAdjustmentCache[$options])) {
270 return $this->termAdjustmentCache[$options];
273 $termQuery = SearchTerm::query()->toBase();
274 $whenStatements = [];
277 foreach ($options->searches as $term) {
278 $whenStatements[] = 'WHEN term LIKE ? THEN ?';
279 $whenBindings[] = $term . '%';
280 $whenBindings[] = $term;
282 $termQuery->orWhere('term', 'like', $term . '%');
285 $case = 'CASE ' . implode(' ', $whenStatements) . ' END';
286 $termQuery->selectRaw($case . ' as term', $whenBindings);
287 $termQuery->selectRaw('COUNT(*) as count');
288 $termQuery->groupByRaw($case, $whenBindings);
290 $termCounts = $termQuery->pluck('count', 'term')->toArray();
291 $adjusted = $this->rawTermCountsToAdjustments($termCounts);
293 $this->termAdjustmentCache[$options] = $adjusted;
295 return $this->termAdjustmentCache[$options];
299 * Convert counts of terms into a relative-count normalised multiplier.
301 * @param array<string, int> $termCounts
303 * @return array<string, int>
305 protected function rawTermCountsToAdjustments(array $termCounts): array
307 if (empty($termCounts)) {
312 $max = max(array_values($termCounts));
314 foreach ($termCounts as $term => $count) {
315 $percent = round($count / $max, 5);
316 $multipliers[$term] = 1.3 - $percent;
323 * Get the available query operators as a regex escaped list.
325 protected function getRegexEscapedOperators(): string
327 $escapedOperators = [];
328 foreach ($this->queryOperators as $operator) {
329 $escapedOperators[] = preg_quote($operator);
332 return implode('|', $escapedOperators);
336 * Apply a tag search term onto a entity query.
338 protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
340 preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit);
341 $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
342 $tagName = $tagSplit[1];
343 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
344 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
345 $validOperator = in_array($tagOperator, $this->queryOperators);
346 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
347 if (!empty($tagName)) {
348 $query->where('name', '=', $tagName);
350 if (is_numeric($tagValue) && $tagOperator !== 'like') {
351 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
352 // search the value as a string which prevents being able to do number-based operations
353 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
354 /** @var Connection $connection */
355 $connection = $query->getConnection();
356 $tagValue = (float) trim($connection->getPdo()->quote($tagValue), "'");
357 $query->whereRaw("value {$tagOperator} {$tagValue}");
359 if ($tagOperator === 'like') {
360 $tagValue = str_replace('\\', '\\\\', $tagValue);
362 $query->where('value', $tagOperator, $tagValue);
365 $query->where('name', '=', $tagName);
373 * Custom entity search filters.
375 protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input): void
378 $date = date_create($input);
379 $query->where('updated_at', '>=', $date);
380 } catch (\Exception $e) {
384 protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input): void
387 $date = date_create($input);
388 $query->where('updated_at', '<', $date);
389 } catch (\Exception $e) {
393 protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input): void
396 $date = date_create($input);
397 $query->where('created_at', '>=', $date);
398 } catch (\Exception $e) {
402 protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
405 $date = date_create($input);
406 $query->where('created_at', '<', $date);
407 } catch (\Exception $e) {
411 protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
413 $userSlug = $input === 'me' ? user()->slug : trim($input);
414 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
416 $query->where('created_by', '=', $user->id);
420 protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
422 $userSlug = $input === 'me' ? user()->slug : trim($input);
423 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
425 $query->where('updated_by', '=', $user->id);
429 protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
431 $userSlug = $input === 'me' ? user()->slug : trim($input);
432 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
434 $query->where('owned_by', '=', $user->id);
438 protected function filterInName(EloquentBuilder $query, Entity $model, $input)
440 $query->where('name', 'like', '%' . $input . '%');
443 protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
445 $this->filterInName($query, $model, $input);
448 protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
450 $query->where($model->textField, 'like', '%' . $input . '%');
453 protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
455 $query->whereHas('permissions');
458 protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
460 $query->whereHas('views', function ($query) {
461 $query->where('user_id', '=', user()->id);
465 protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
467 $query->whereDoesntHave('views', function ($query) {
468 $query->where('user_id', '=', user()->id);
472 protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
474 $functionName = Str::camel('sort_by_' . $input);
475 if (method_exists($this, $functionName)) {
476 $this->$functionName($query, $model);
481 * Sorting filter options.
483 protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
485 $commentsTable = DB::getTablePrefix() . 'comments';
486 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
487 $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');
489 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');