3 namespace BookStack\Entities\Tools;
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;
24 protected EntityProvider $entityProvider;
25 protected PermissionApplicator $permissions;
28 * Acceptable operators to be used in a query.
32 protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
35 * Retain a cache of score adjusted terms for specific search options.
36 * From PHP>=8 this can be made into a WeakMap instead.
38 * @var SplObjectStorage
40 protected $termAdjustmentCache;
42 public function __construct(EntityProvider $entityProvider, PermissionApplicator $permissions)
44 $this->entityProvider = $entityProvider;
45 $this->permissions = $permissions;
46 $this->termAdjustmentCache = new SplObjectStorage();
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.
54 * @return array{total: int, count: int, has_more: bool, results: Entity[]}
56 public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20): array
58 $entityTypes = array_keys($this->entityProvider->all());
59 $entityTypesToSearch = $entityTypes;
61 if ($entityType !== 'all') {
62 $entityTypesToSearch = $entityType;
63 } elseif (isset($searchOpts->filters['type'])) {
64 $entityTypesToSearch = explode('|', $searchOpts->filters['type']);
71 foreach ($entityTypesToSearch as $entityType) {
72 if (!in_array($entityType, $entityTypes)) {
76 $entityModelInstance = $this->entityProvider->get($entityType);
77 $searchQuery = $this->buildQuery($searchOpts, $entityModelInstance);
78 $entityTotal = $searchQuery->count();
79 $searchResults = $this->getPageOfDataFromQuery($searchQuery, $entityModelInstance, $page, $count);
81 if ($entityTotal > ($page * $count)) {
85 $total += $entityTotal;
86 $results = $results->merge($searchResults);
91 'count' => count($results),
92 'has_more' => $hasMore,
93 'results' => $results->sortByDesc('score')->values(),
98 * Search a book for entities.
100 public function searchBook(int $bookId, string $searchString): Collection
102 $opts = SearchOptions::fromString($searchString);
103 $entityTypes = ['page', 'chapter'];
104 $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
106 $results = collect();
107 foreach ($entityTypesToSearch as $entityType) {
108 if (!in_array($entityType, $entityTypes)) {
112 $entityModelInstance = $this->entityProvider->get($entityType);
113 $search = $this->buildQuery($opts, $entityModelInstance)->where('book_id', '=', $bookId)->take(20)->get();
114 $results = $results->merge($search);
117 return $results->sortByDesc('score')->take(20);
121 * Search a chapter for entities.
123 public function searchChapter(int $chapterId, string $searchString): Collection
125 $opts = SearchOptions::fromString($searchString);
126 $entityModelInstance = $this->entityProvider->get('page');
127 $pages = $this->buildQuery($opts, $entityModelInstance)->where('chapter_id', '=', $chapterId)->take(20)->get();
129 return $pages->sortByDesc('score');
133 * Get a page of result data from the given query based on the provided page parameters.
135 protected function getPageOfDataFromQuery(EloquentBuilder $query, Entity $entityModelInstance, int $page = 1, int $count = 20): EloquentCollection
137 $relations = ['tags'];
139 if ($entityModelInstance instanceof BookChild) {
140 $relations['book'] = function (BelongsTo $query) {
141 $query->scopes('visible');
145 if ($entityModelInstance instanceof Page) {
146 $relations['chapter'] = function (BelongsTo $query) {
147 $query->scopes('visible');
151 return $query->clone()
152 ->with(array_filter($relations))
153 ->skip(($page - 1) * $count)
159 * Create a search query for an entity.
161 protected function buildQuery(SearchOptions $searchOpts, Entity $entityModelInstance): EloquentBuilder
163 $entityQuery = $entityModelInstance->newQuery()->scopes('visible');
165 if ($entityModelInstance instanceof Page) {
166 $entityQuery->select($entityModelInstance::$listAttributes);
168 $entityQuery->select(['*']);
171 // Handle normal search terms
172 $this->applyTermSearch($entityQuery, $searchOpts, $entityModelInstance);
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 . '%');
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 $query->orWhere('term', 'like', $inputTerm . '%');
225 $subQuery->groupBy('entity_type', 'entity_id');
227 $entityQuery->joinSub($subQuery, 's', 'id', '=', 'entity_id');
228 $entityQuery->addSelect('s.score');
229 $entityQuery->orderBy('score', 'desc');
233 * Create a select statement, with prepared bindings, for the given
234 * set of scored search terms.
236 * @param array<string, float> $scoredTerms
238 * @return array{statement: string, bindings: string[]}
240 protected function selectForScoredTerms(array $scoredTerms): array
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).
248 foreach ($scoredTerms as $term => $score) {
249 $ifChain = 'IF(term like ?, score * ' . (float) $score . ', ' . $ifChain . ')';
250 $bindings[] = $term . '%';
254 'statement' => 'SUM(' . $ifChain . ') as score',
255 'bindings' => array_reverse($bindings),
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.
264 * @return array<string, float>
266 protected function getTermAdjustments(SearchOptions $options): array
268 if (isset($this->termAdjustmentCache[$options])) {
269 return $this->termAdjustmentCache[$options];
272 $termQuery = SearchTerm::query()->toBase();
273 $whenStatements = [];
276 foreach ($options->searches as $term) {
277 $whenStatements[] = 'WHEN term LIKE ? THEN ?';
278 $whenBindings[] = $term . '%';
279 $whenBindings[] = $term;
281 $termQuery->orWhere('term', 'like', $term . '%');
284 $case = 'CASE ' . implode(' ', $whenStatements) . ' END';
285 $termQuery->selectRaw($case . ' as term', $whenBindings);
286 $termQuery->selectRaw('COUNT(*) as count');
287 $termQuery->groupByRaw($case, $whenBindings);
289 $termCounts = $termQuery->pluck('count', 'term')->toArray();
290 $adjusted = $this->rawTermCountsToAdjustments($termCounts);
292 $this->termAdjustmentCache[$options] = $adjusted;
294 return $this->termAdjustmentCache[$options];
298 * Convert counts of terms into a relative-count normalised multiplier.
300 * @param array<string, int> $termCounts
302 * @return array<string, int>
304 protected function rawTermCountsToAdjustments(array $termCounts): array
306 if (empty($termCounts)) {
311 $max = max(array_values($termCounts));
313 foreach ($termCounts as $term => $count) {
314 $percent = round($count / $max, 5);
315 $multipliers[$term] = 1.3 - $percent;
322 * Get the available query operators as a regex escaped list.
324 protected function getRegexEscapedOperators(): string
326 $escapedOperators = [];
327 foreach ($this->queryOperators as $operator) {
328 $escapedOperators[] = preg_quote($operator);
331 return implode('|', $escapedOperators);
335 * Apply a tag search term onto a entity query.
337 protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
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);
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}");
358 $query->where('value', $tagOperator, $tagValue);
361 $query->where('name', '=', $tagName);
369 * Custom entity search filters.
371 protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input): void
374 $date = date_create($input);
375 $query->where('updated_at', '>=', $date);
376 } catch (\Exception $e) {
380 protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input): void
383 $date = date_create($input);
384 $query->where('updated_at', '<', $date);
385 } catch (\Exception $e) {
389 protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input): void
392 $date = date_create($input);
393 $query->where('created_at', '>=', $date);
394 } catch (\Exception $e) {
398 protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
401 $date = date_create($input);
402 $query->where('created_at', '<', $date);
403 } catch (\Exception $e) {
407 protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
409 $userSlug = $input === 'me' ? user()->slug : trim($input);
410 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
412 $query->where('created_by', '=', $user->id);
416 protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
418 $userSlug = $input === 'me' ? user()->slug : trim($input);
419 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
421 $query->where('updated_by', '=', $user->id);
425 protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
427 $userSlug = $input === 'me' ? user()->slug : trim($input);
428 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
430 $query->where('owned_by', '=', $user->id);
434 protected function filterInName(EloquentBuilder $query, Entity $model, $input)
436 $query->where('name', 'like', '%' . $input . '%');
439 protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
441 $this->filterInName($query, $model, $input);
444 protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
446 $query->where($model->textField, 'like', '%' . $input . '%');
449 protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
451 $query->where('restricted', '=', true);
454 protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
456 $query->whereHas('views', function ($query) {
457 $query->where('user_id', '=', user()->id);
461 protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
463 $query->whereDoesntHave('views', function ($query) {
464 $query->where('user_id', '=', user()->id);
468 protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
470 $functionName = Str::camel('sort_by_' . $input);
471 if (method_exists($this, $functionName)) {
472 $this->$functionName($query, $model);
477 * Sorting filter options.
479 protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
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');
485 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');