3 namespace BookStack\Search;
5 use BookStack\Entities\EntityProvider;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Entities\Queries\EntityQueries;
8 use BookStack\Entities\Tools\EntityHydrator;
9 use BookStack\Permissions\PermissionApplicator;
10 use BookStack\Search\Options\TagSearchOption;
11 use BookStack\Users\Models\User;
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\Query\Builder;
16 use Illuminate\Database\Query\JoinClause;
17 use Illuminate\Support\Collection;
18 use Illuminate\Support\Facades\DB;
19 use Illuminate\Support\Str;
25 * Retain a cache of score-adjusted terms for specific search options.
27 protected WeakMap $termAdjustmentCache;
29 public function __construct(
30 protected EntityProvider $entityProvider,
31 protected PermissionApplicator $permissions,
32 protected EntityQueries $entityQueries,
34 $this->termAdjustmentCache = new WeakMap();
38 * Search all entities in the system.
39 * The provided count is for each entity to search,
40 * Total returned could be larger and not guaranteed.
41 * // TODO - Update this comment
43 * @return array{total: int, count: int, has_more: bool, results: Collection<Entity>}
45 public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20): array
47 $entityTypes = array_keys($this->entityProvider->all());
48 $entityTypesToSearch = $entityTypes;
50 $filterMap = $searchOpts->filters->toValueMap();
51 if ($entityType !== 'all') {
52 $entityTypesToSearch = [$entityType];
53 } elseif (isset($filterMap['type'])) {
54 $entityTypesToSearch = explode('|', $filterMap['type']);
57 $searchQuery = $this->buildQuery($searchOpts, $entityTypesToSearch);
58 $total = $searchQuery->count();
59 $results = $this->getPageOfDataFromQuery($searchQuery, $page, $count);
62 $hasMore = ($total > ($page * $count));
66 'count' => count($results),
67 'has_more' => $hasMore,
68 'results' => $results->sortByDesc('score')->values(),
73 * Search a book for entities.
75 public function searchBook(int $bookId, string $searchString): Collection
77 $opts = SearchOptions::fromString($searchString);
78 $entityTypes = ['page', 'chapter'];
79 $filterMap = $opts->filters->toValueMap();
80 $entityTypesToSearch = isset($filterMap['type']) ? explode('|', $filterMap['type']) : $entityTypes;
83 foreach ($entityTypesToSearch as $entityType) {
84 if (!in_array($entityType, $entityTypes)) {
88 $search = $this->buildQuery($opts, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
89 $results = $results->merge($search);
92 return $results->sortByDesc('score')->take(20);
96 * Search a chapter for entities.
98 public function searchChapter(int $chapterId, string $searchString): Collection
100 $opts = SearchOptions::fromString($searchString);
101 $pages = $this->buildQuery($opts, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
103 return $pages->sortByDesc('score');
107 * Get a page of result data from the given query based on the provided page parameters.
109 protected function getPageOfDataFromQuery(EloquentBuilder $query, int $page, int $count): Collection
111 $entities = $query->clone()
112 ->skip(($page - 1) * $count)
116 $hydrated = (new EntityHydrator($entities->all(), true, true))->hydrate();
118 return collect($hydrated);
122 * Create a search query for an entity.
123 * @param string[] $entityTypes
125 protected function buildQuery(SearchOptions $searchOpts, array $entityTypes): EloquentBuilder
127 $entityQuery = $this->entityQueries->visibleForList()
128 ->whereIn('type', $entityTypes);
130 // Handle normal search terms
131 $this->applyTermSearch($entityQuery, $searchOpts, $entityTypes);
133 // Handle exact term matching
134 foreach ($searchOpts->exacts->all() as $exact) {
135 $filter = function (EloquentBuilder $query) use ($exact) {
136 $inputTerm = str_replace('\\', '\\\\', $exact->value);
137 $query->where('name', 'like', '%' . $inputTerm . '%')
138 ->orWhere('description', 'like', '%' . $inputTerm . '%');
141 $exact->negated ? $entityQuery->whereNot($filter) : $entityQuery->where($filter);
144 // Handle tag searches
145 foreach ($searchOpts->tags->all() as $tagOption) {
146 $this->applyTagSearch($entityQuery, $tagOption);
150 foreach ($searchOpts->filters->all() as $filterOption) {
151 $functionName = Str::camel('filter_' . $filterOption->getKey());
152 if (method_exists($this, $functionName)) {
153 $this->$functionName($entityQuery, $filterOption->value, $filterOption->negated);
161 * For the given search query, apply the queries for handling the regular search terms.
163 protected function applyTermSearch(EloquentBuilder $entityQuery, SearchOptions $options, array $entityTypes): void
165 $terms = $options->searches->toValueArray();
166 if (count($terms) === 0) {
170 $scoredTerms = $this->getTermAdjustments($options);
171 $scoreSelect = $this->selectForScoredTerms($scoredTerms);
173 $subQuery = DB::table('search_terms')->select([
176 DB::raw($scoreSelect['statement']),
179 $subQuery->addBinding($scoreSelect['bindings'], 'select');
180 $subQuery->where(function (Builder $query) use ($terms) {
181 foreach ($terms as $inputTerm) {
182 $escapedTerm = str_replace('\\', '\\\\', $inputTerm);
183 $query->orWhere('term', 'like', $escapedTerm . '%');
186 $subQuery->groupBy('entity_type', 'entity_id');
188 $entityQuery->joinSub($subQuery, 's', function (JoinClause $join) {
189 $join->on('s.entity_id', '=', 'entities.id')
190 ->on('s.entity_type', '=', 'entities.type');
192 $entityQuery->addSelect('s.score');
193 $entityQuery->orderBy('score', 'desc');
197 * Create a select statement, with prepared bindings, for the given
198 * set of scored search terms.
200 * @param array<string, float> $scoredTerms
202 * @return array{statement: string, bindings: string[]}
204 protected function selectForScoredTerms(array $scoredTerms): array
206 // Within this we walk backwards to create the chain of 'if' statements
207 // so that each previous statement is used in the 'else' condition of
208 // the next (earlier) to be built. We start at '0' to have no score
209 // on no match (Should never actually get to this case).
212 foreach ($scoredTerms as $term => $score) {
213 $ifChain = 'IF(term like ?, score * ' . (float) $score . ', ' . $ifChain . ')';
214 $bindings[] = $term . '%';
218 'statement' => 'SUM(' . $ifChain . ') as score',
219 'bindings' => array_reverse($bindings),
224 * For the terms in the given search options, query their popularity across all
225 * search terms then provide that back as score adjustment multiplier applicable
226 * for their rarity. Returns an array of float multipliers, keyed by term.
228 * @return array<string, float>
230 protected function getTermAdjustments(SearchOptions $options): array
232 if (isset($this->termAdjustmentCache[$options])) {
233 return $this->termAdjustmentCache[$options];
236 $termQuery = SearchTerm::query()->toBase();
237 $whenStatements = [];
240 foreach ($options->searches->toValueArray() as $term) {
241 $whenStatements[] = 'WHEN term LIKE ? THEN ?';
242 $whenBindings[] = $term . '%';
243 $whenBindings[] = $term;
245 $termQuery->orWhere('term', 'like', $term . '%');
248 $case = 'CASE ' . implode(' ', $whenStatements) . ' END';
249 $termQuery->selectRaw($case . ' as term', $whenBindings);
250 $termQuery->selectRaw('COUNT(*) as count');
251 $termQuery->groupByRaw($case, $whenBindings);
253 $termCounts = $termQuery->pluck('count', 'term')->toArray();
254 $adjusted = $this->rawTermCountsToAdjustments($termCounts);
256 $this->termAdjustmentCache[$options] = $adjusted;
258 return $this->termAdjustmentCache[$options];
262 * Convert counts of terms into a relative-count normalised multiplier.
264 * @param array<string, int> $termCounts
266 * @return array<string, float>
268 protected function rawTermCountsToAdjustments(array $termCounts): array
270 if (empty($termCounts)) {
275 $max = max(array_values($termCounts));
277 foreach ($termCounts as $term => $count) {
278 $percent = round($count / $max, 5);
279 $multipliers[$term] = 1.3 - $percent;
286 * Apply a tag search term onto an entity query.
288 protected function applyTagSearch(EloquentBuilder $query, TagSearchOption $option): void
290 $filter = function (EloquentBuilder $query) use ($option): void {
291 $tagParts = $option->getParts();
292 if (empty($tagParts['operator']) || empty($tagParts['value'])) {
293 $query->where('name', '=', $tagParts['name']);
297 if (!empty($tagParts['name'])) {
298 $query->where('name', '=', $tagParts['name']);
301 if (is_numeric($tagParts['value']) && $tagParts['operator'] !== 'like') {
302 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
303 // search the value as a string which prevents being able to do number-based operations
304 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
305 /** @var Connection $connection */
306 $connection = $query->getConnection();
307 $quotedValue = (float) trim($connection->getPdo()->quote($tagParts['value']), "'");
308 $query->whereRaw("value {$tagParts['operator']} {$quotedValue}");
309 } else if ($tagParts['operator'] === 'like') {
310 $query->where('value', $tagParts['operator'], str_replace('\\', '\\\\', $tagParts['value']));
312 $query->where('value', $tagParts['operator'], $tagParts['value']);
316 $option->negated ? $query->whereDoesntHave('tags', $filter) : $query->whereHas('tags', $filter);
319 protected function applyNegatableWhere(EloquentBuilder $query, bool $negated, string $column, string $operator, mixed $value): void
322 $query->whereNot($column, $operator, $value);
324 $query->where($column, $operator, $value);
329 * Custom entity search filters.
331 protected function filterUpdatedAfter(EloquentBuilder $query, string $input, bool $negated): void
333 $date = date_create($input);
334 $this->applyNegatableWhere($query, $negated, 'updated_at', '>=', $date);
337 protected function filterUpdatedBefore(EloquentBuilder $query, string $input, bool $negated): void
339 $date = date_create($input);
340 $this->applyNegatableWhere($query, $negated, 'updated_at', '<', $date);
343 protected function filterCreatedAfter(EloquentBuilder $query, string $input, bool $negated): void
345 $date = date_create($input);
346 $this->applyNegatableWhere($query, $negated, 'created_at', '>=', $date);
349 protected function filterCreatedBefore(EloquentBuilder $query, string $input, bool $negated)
351 $date = date_create($input);
352 $this->applyNegatableWhere($query, $negated, 'created_at', '<', $date);
355 protected function filterCreatedBy(EloquentBuilder $query, string $input, bool $negated)
357 $userSlug = $input === 'me' ? user()->slug : trim($input);
358 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
360 $this->applyNegatableWhere($query, $negated, 'created_by', '=', $user->id);
364 protected function filterUpdatedBy(EloquentBuilder $query, string $input, bool $negated)
366 $userSlug = $input === 'me' ? user()->slug : trim($input);
367 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
369 $this->applyNegatableWhere($query, $negated, 'updated_by', '=', $user->id);
373 protected function filterOwnedBy(EloquentBuilder $query, string $input, bool $negated)
375 $userSlug = $input === 'me' ? user()->slug : trim($input);
376 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
378 $this->applyNegatableWhere($query, $negated, 'owned_by', '=', $user->id);
382 protected function filterInName(EloquentBuilder $query, string $input, bool $negated)
384 $this->applyNegatableWhere($query, $negated, 'name', 'like', '%' . $input . '%');
387 protected function filterInTitle(EloquentBuilder $query, string $input, bool $negated)
389 $this->filterInName($query, $input, $negated);
392 protected function filterInBody(EloquentBuilder $query, string $input, bool $negated)
394 $this->applyNegatableWhere($query, $negated, 'description', 'like', '%' . $input . '%');
397 protected function filterIsRestricted(EloquentBuilder $query, string $input, bool $negated)
399 $negated ? $query->whereDoesntHave('permissions') : $query->whereHas('permissions');
402 protected function filterViewedByMe(EloquentBuilder $query, string $input, bool $negated)
404 $filter = function ($query) {
405 $query->where('user_id', '=', user()->id);
408 $negated ? $query->whereDoesntHave('views', $filter) : $query->whereHas('views', $filter);
411 protected function filterNotViewedByMe(EloquentBuilder $query, string $input, bool $negated)
413 $filter = function ($query) {
414 $query->where('user_id', '=', user()->id);
417 $negated ? $query->whereHas('views', $filter) : $query->whereDoesntHave('views', $filter);
420 protected function filterIsTemplate(EloquentBuilder $query, string $input, bool $negated)
422 $this->applyNegatableWhere($query, $negated, 'template', '=', true);
425 protected function filterSortBy(EloquentBuilder $query, string $input, bool $negated)
427 $functionName = Str::camel('sort_by_' . $input);
428 if (method_exists($this, $functionName)) {
429 $this->$functionName($query, $negated);
434 * Sorting filter options.
436 protected function sortByLastCommented(EloquentBuilder $query, bool $negated)
438 $commentsTable = DB::getTablePrefix() . 'comments';
439 $commentQuery = DB::raw('(SELECT c1.commentable_id, c1.commentable_type, c1.created_at as last_commented FROM ' . $commentsTable . ' c1 LEFT JOIN ' . $commentsTable . ' c2 ON (c1.commentable_id = c2.commentable_id AND c1.commentable_type = c2.commentable_type AND c1.created_at < c2.created_at) WHERE c2.created_at IS NULL) as comments');
441 $query->join($commentQuery, function (JoinClause $join) {
442 $join->on('entities.id', '=', 'comments.commentable_id')
443 ->on('entities.type', '=', 'comments.commentable_type');
444 })->orderBy('last_commented', $negated ? 'asc' : 'desc');