3 namespace BookStack\Search;
5 use BookStack\Entities\EntityProvider;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Entities\Models\Page;
8 use BookStack\Entities\Queries\EntityQueries;
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;
24 * Acceptable operators to be used in a query.
28 protected array $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
31 * Retain a cache of score adjusted terms for specific search options.
32 * From PHP>=8 this can be made into a WeakMap instead.
34 * @var SplObjectStorage
36 protected $termAdjustmentCache;
38 public function __construct(
39 protected EntityProvider $entityProvider,
40 protected PermissionApplicator $permissions,
41 protected EntityQueries $entityQueries,
43 $this->termAdjustmentCache = new SplObjectStorage();
47 * Search all entities in the system.
48 * The provided count is for each entity to search,
49 * Total returned could be larger and not guaranteed.
51 * @return array{total: int, count: int, has_more: bool, results: Collection<Entity>}
53 public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20): array
55 $entityTypes = array_keys($this->entityProvider->all());
56 $entityTypesToSearch = $entityTypes;
58 if ($entityType !== 'all') {
59 $entityTypesToSearch = [$entityType];
60 } elseif (isset($searchOpts->filters['type'])) {
61 $entityTypesToSearch = explode('|', $searchOpts->filters['type']);
68 foreach ($entityTypesToSearch as $entityType) {
69 if (!in_array($entityType, $entityTypes)) {
73 $searchQuery = $this->buildQuery($searchOpts, $entityType);
74 $entityTotal = $searchQuery->count();
75 $searchResults = $this->getPageOfDataFromQuery($searchQuery, $entityType, $page, $count);
77 if ($entityTotal > ($page * $count)) {
81 $total += $entityTotal;
82 $results = $results->merge($searchResults);
87 'count' => count($results),
88 'has_more' => $hasMore,
89 'results' => $results->sortByDesc('score')->values(),
94 * Search a book for entities.
96 public function searchBook(int $bookId, string $searchString): Collection
98 $opts = SearchOptions::fromString($searchString);
99 $entityTypes = ['page', 'chapter'];
100 $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
102 $results = collect();
103 foreach ($entityTypesToSearch as $entityType) {
104 if (!in_array($entityType, $entityTypes)) {
108 $search = $this->buildQuery($opts, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
109 $results = $results->merge($search);
112 return $results->sortByDesc('score')->take(20);
116 * Search a chapter for entities.
118 public function searchChapter(int $chapterId, string $searchString): Collection
120 $opts = SearchOptions::fromString($searchString);
121 $pages = $this->buildQuery($opts, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
123 return $pages->sortByDesc('score');
127 * Get a page of result data from the given query based on the provided page parameters.
129 protected function getPageOfDataFromQuery(EloquentBuilder $query, string $entityType, int $page = 1, int $count = 20): EloquentCollection
131 $relations = ['tags'];
133 if ($entityType === 'page' || $entityType === 'chapter') {
134 $relations['book'] = function (BelongsTo $query) {
135 $query->scopes('visible');
139 if ($entityType === 'page') {
140 $relations['chapter'] = function (BelongsTo $query) {
141 $query->scopes('visible');
145 return $query->clone()
146 ->with(array_filter($relations))
147 ->skip(($page - 1) * $count)
153 * Create a search query for an entity.
155 protected function buildQuery(SearchOptions $searchOpts, string $entityType): EloquentBuilder
157 $entityModelInstance = $this->entityProvider->get($entityType);
158 $entityQuery = $this->entityQueries->visibleForList($entityType);
160 // Handle normal search terms
161 $this->applyTermSearch($entityQuery, $searchOpts, $entityType);
163 // Handle exact term matching
164 foreach ($searchOpts->exacts as $inputTerm) {
165 $entityQuery->where(function (EloquentBuilder $query) use ($inputTerm, $entityModelInstance) {
166 $inputTerm = str_replace('\\', '\\\\', $inputTerm);
167 $query->where('name', 'like', '%' . $inputTerm . '%')
168 ->orWhere($entityModelInstance->textField, 'like', '%' . $inputTerm . '%');
172 // Handle tag searches
173 foreach ($searchOpts->tags as $inputTerm) {
174 $this->applyTagSearch($entityQuery, $inputTerm);
178 foreach ($searchOpts->filters as $filterTerm => $filterValue) {
179 $functionName = Str::camel('filter_' . $filterTerm);
180 if (method_exists($this, $functionName)) {
181 $this->$functionName($entityQuery, $entityModelInstance, $filterValue);
189 * For the given search query, apply the queries for handling the regular search terms.
191 protected function applyTermSearch(EloquentBuilder $entityQuery, SearchOptions $options, string $entityType): void
193 $terms = $options->searches;
194 if (count($terms) === 0) {
198 $scoredTerms = $this->getTermAdjustments($options);
199 $scoreSelect = $this->selectForScoredTerms($scoredTerms);
201 $subQuery = DB::table('search_terms')->select([
204 DB::raw($scoreSelect['statement']),
207 $subQuery->addBinding($scoreSelect['bindings'], 'select');
209 $subQuery->where('entity_type', '=', $entityType);
210 $subQuery->where(function (Builder $query) use ($terms) {
211 foreach ($terms as $inputTerm) {
212 $inputTerm = str_replace('\\', '\\\\', $inputTerm);
213 $query->orWhere('term', 'like', $inputTerm . '%');
216 $subQuery->groupBy('entity_type', 'entity_id');
218 $entityQuery->joinSub($subQuery, 's', 'id', '=', 'entity_id');
219 $entityQuery->addSelect('s.score');
220 $entityQuery->orderBy('score', 'desc');
224 * Create a select statement, with prepared bindings, for the given
225 * set of scored search terms.
227 * @param array<string, float> $scoredTerms
229 * @return array{statement: string, bindings: string[]}
231 protected function selectForScoredTerms(array $scoredTerms): array
233 // Within this we walk backwards to create the chain of 'if' statements
234 // so that each previous statement is used in the 'else' condition of
235 // the next (earlier) to be built. We start at '0' to have no score
236 // on no match (Should never actually get to this case).
239 foreach ($scoredTerms as $term => $score) {
240 $ifChain = 'IF(term like ?, score * ' . (float) $score . ', ' . $ifChain . ')';
241 $bindings[] = $term . '%';
245 'statement' => 'SUM(' . $ifChain . ') as score',
246 'bindings' => array_reverse($bindings),
251 * For the terms in the given search options, query their popularity across all
252 * search terms then provide that back as score adjustment multiplier applicable
253 * for their rarity. Returns an array of float multipliers, keyed by term.
255 * @return array<string, float>
257 protected function getTermAdjustments(SearchOptions $options): array
259 if (isset($this->termAdjustmentCache[$options])) {
260 return $this->termAdjustmentCache[$options];
263 $termQuery = SearchTerm::query()->toBase();
264 $whenStatements = [];
267 foreach ($options->searches as $term) {
268 $whenStatements[] = 'WHEN term LIKE ? THEN ?';
269 $whenBindings[] = $term . '%';
270 $whenBindings[] = $term;
272 $termQuery->orWhere('term', 'like', $term . '%');
275 $case = 'CASE ' . implode(' ', $whenStatements) . ' END';
276 $termQuery->selectRaw($case . ' as term', $whenBindings);
277 $termQuery->selectRaw('COUNT(*) as count');
278 $termQuery->groupByRaw($case, $whenBindings);
280 $termCounts = $termQuery->pluck('count', 'term')->toArray();
281 $adjusted = $this->rawTermCountsToAdjustments($termCounts);
283 $this->termAdjustmentCache[$options] = $adjusted;
285 return $this->termAdjustmentCache[$options];
289 * Convert counts of terms into a relative-count normalised multiplier.
291 * @param array<string, int> $termCounts
293 * @return array<string, int>
295 protected function rawTermCountsToAdjustments(array $termCounts): array
297 if (empty($termCounts)) {
302 $max = max(array_values($termCounts));
304 foreach ($termCounts as $term => $count) {
305 $percent = round($count / $max, 5);
306 $multipliers[$term] = 1.3 - $percent;
313 * Get the available query operators as a regex escaped list.
315 protected function getRegexEscapedOperators(): string
317 $escapedOperators = [];
318 foreach ($this->queryOperators as $operator) {
319 $escapedOperators[] = preg_quote($operator);
322 return implode('|', $escapedOperators);
326 * Apply a tag search term onto a entity query.
328 protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
330 preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit);
331 $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
332 $tagName = $tagSplit[1];
333 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
334 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
335 $validOperator = in_array($tagOperator, $this->queryOperators);
336 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
337 if (!empty($tagName)) {
338 $query->where('name', '=', $tagName);
340 if (is_numeric($tagValue) && $tagOperator !== 'like') {
341 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
342 // search the value as a string which prevents being able to do number-based operations
343 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
344 /** @var Connection $connection */
345 $connection = $query->getConnection();
346 $tagValue = (float) trim($connection->getPdo()->quote($tagValue), "'");
347 $query->whereRaw("value {$tagOperator} {$tagValue}");
349 if ($tagOperator === 'like') {
350 $tagValue = str_replace('\\', '\\\\', $tagValue);
352 $query->where('value', $tagOperator, $tagValue);
355 $query->where('name', '=', $tagName);
363 * Custom entity search filters.
365 protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input): void
368 $date = date_create($input);
369 $query->where('updated_at', '>=', $date);
370 } catch (\Exception $e) {
374 protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input): void
377 $date = date_create($input);
378 $query->where('updated_at', '<', $date);
379 } catch (\Exception $e) {
383 protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input): void
386 $date = date_create($input);
387 $query->where('created_at', '>=', $date);
388 } catch (\Exception $e) {
392 protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
395 $date = date_create($input);
396 $query->where('created_at', '<', $date);
397 } catch (\Exception $e) {
401 protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
403 $userSlug = $input === 'me' ? user()->slug : trim($input);
404 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
406 $query->where('created_by', '=', $user->id);
410 protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
412 $userSlug = $input === 'me' ? user()->slug : trim($input);
413 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
415 $query->where('updated_by', '=', $user->id);
419 protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
421 $userSlug = $input === 'me' ? user()->slug : trim($input);
422 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
424 $query->where('owned_by', '=', $user->id);
428 protected function filterInName(EloquentBuilder $query, Entity $model, $input)
430 $query->where('name', 'like', '%' . $input . '%');
433 protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
435 $this->filterInName($query, $model, $input);
438 protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
440 $query->where($model->textField, 'like', '%' . $input . '%');
443 protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
445 $query->whereHas('permissions');
448 protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
450 $query->whereHas('views', function ($query) {
451 $query->where('user_id', '=', user()->id);
455 protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
457 $query->whereDoesntHave('views', function ($query) {
458 $query->where('user_id', '=', user()->id);
462 protected function filterIsTemplate(EloquentBuilder $query, Entity $model, $input)
464 if ($model instanceof Page) {
465 $query->where('template', '=', true);
469 protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
471 $functionName = Str::camel('sort_by_' . $input);
472 if (method_exists($this, $functionName)) {
473 $this->$functionName($query, $model);
478 * Sorting filter options.
480 protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
482 $commentsTable = DB::getTablePrefix() . 'comments';
483 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
484 $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');
486 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');