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;
25 protected EntityProvider $entityProvider;
26 protected PermissionApplicator $permissions;
29 * Acceptable operators to be used in a query.
33 protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
36 * Retain a cache of score adjusted terms for specific search options.
37 * From PHP>=8 this can be made into a WeakMap instead.
39 * @var SplObjectStorage
41 protected $termAdjustmentCache;
43 public function __construct(EntityProvider $entityProvider, PermissionApplicator $permissions)
45 $this->entityProvider = $entityProvider;
46 $this->permissions = $permissions;
47 $this->termAdjustmentCache = new SplObjectStorage();
51 * Search all entities in the system.
52 * The provided count is for each entity to search,
53 * Total returned could be larger and not guaranteed.
55 * @return array{total: int, count: int, has_more: bool, results: Entity[]}
57 public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20): array
59 $entityTypes = array_keys($this->entityProvider->all());
60 $entityTypesToSearch = $entityTypes;
62 if ($entityType !== 'all') {
63 $entityTypesToSearch = $entityType;
64 } elseif (isset($searchOpts->filters['type'])) {
65 $entityTypesToSearch = explode('|', $searchOpts->filters['type']);
72 foreach ($entityTypesToSearch as $entityType) {
73 if (!in_array($entityType, $entityTypes)) {
77 $entityModelInstance = $this->entityProvider->get($entityType);
78 $searchQuery = $this->buildQuery($searchOpts, $entityModelInstance);
79 $entityTotal = $searchQuery->count();
80 $searchResults = $this->getPageOfDataFromQuery($searchQuery, $entityModelInstance, $page, $count);
82 if ($entityTotal > ($page * $count)) {
86 $total += $entityTotal;
87 $results = $results->merge($searchResults);
92 'count' => count($results),
93 'has_more' => $hasMore,
94 'results' => $results->sortByDesc('score')->values(),
99 * Search a book for entities.
101 public function searchBook(int $bookId, string $searchString): Collection
103 $opts = SearchOptions::fromString($searchString);
104 $entityTypes = ['page', 'chapter'];
105 $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
107 $results = collect();
108 foreach ($entityTypesToSearch as $entityType) {
109 if (!in_array($entityType, $entityTypes)) {
113 $entityModelInstance = $this->entityProvider->get($entityType);
114 $search = $this->buildQuery($opts, $entityModelInstance)->where('book_id', '=', $bookId)->take(20)->get();
115 $results = $results->merge($search);
118 return $results->sortByDesc('score')->take(20);
122 * Search a chapter for entities.
124 public function searchChapter(int $chapterId, string $searchString): Collection
126 $opts = SearchOptions::fromString($searchString);
127 $entityModelInstance = $this->entityProvider->get('page');
128 $pages = $this->buildQuery($opts, $entityModelInstance)->where('chapter_id', '=', $chapterId)->take(20)->get();
130 return $pages->sortByDesc('score');
134 * Get a page of result data from the given query based on the provided page parameters.
136 protected function getPageOfDataFromQuery(EloquentBuilder $query, Entity $entityModelInstance, int $page = 1, int $count = 20): EloquentCollection
138 $relations = ['tags'];
140 if ($entityModelInstance instanceof BookChild) {
141 $relations['book'] = function (BelongsTo $query) {
142 $query->scopes('visible');
146 if ($entityModelInstance instanceof Page) {
147 $relations['chapter'] = function (BelongsTo $query) {
148 $query->scopes('visible');
152 return $query->clone()
153 ->with(array_filter($relations))
154 ->skip(($page - 1) * $count)
160 * Create a search query for an entity.
162 protected function buildQuery(SearchOptions $searchOpts, Entity $entityModelInstance): EloquentBuilder
164 $entityQuery = $entityModelInstance->newQuery();
166 if ($entityModelInstance instanceof Page) {
167 $entityQuery->select($entityModelInstance::$listAttributes);
169 $entityQuery->select(['*']);
172 // Handle normal search terms
173 $this->applyTermSearch($entityQuery, $searchOpts, $entityModelInstance);
175 // Handle exact term matching
176 foreach ($searchOpts->exacts as $inputTerm) {
177 $entityQuery->where(function (EloquentBuilder $query) use ($inputTerm, $entityModelInstance) {
178 $query->where('name', 'like', '%' . $inputTerm . '%')
179 ->orWhere($entityModelInstance->textField, 'like', '%' . $inputTerm . '%');
183 // Handle tag searches
184 foreach ($searchOpts->tags as $inputTerm) {
185 $this->applyTagSearch($entityQuery, $inputTerm);
189 foreach ($searchOpts->filters as $filterTerm => $filterValue) {
190 $functionName = Str::camel('filter_' . $filterTerm);
191 if (method_exists($this, $functionName)) {
192 $this->$functionName($entityQuery, $entityModelInstance, $filterValue);
196 return $this->permissions->enforceEntityRestrictions($entityModelInstance, $entityQuery);
200 * For the given search query, apply the queries for handling the regular search terms.
202 protected function applyTermSearch(EloquentBuilder $entityQuery, SearchOptions $options, Entity $entity): void
204 $terms = $options->searches;
205 if (count($terms) === 0) {
209 $scoredTerms = $this->getTermAdjustments($options);
210 $scoreSelect = $this->selectForScoredTerms($scoredTerms);
212 $subQuery = DB::table('search_terms')->select([
215 DB::raw($scoreSelect['statement']),
218 $subQuery->addBinding($scoreSelect['bindings'], 'select');
220 $subQuery->where('entity_type', '=', $entity->getMorphClass());
221 $subQuery->where(function (Builder $query) use ($terms) {
222 foreach ($terms as $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 $query->where('value', $tagOperator, $tagValue);
362 $query->where('name', '=', $tagName);
370 * Custom entity search filters.
372 protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input): void
375 $date = date_create($input);
376 $query->where('updated_at', '>=', $date);
377 } catch (\Exception $e) {
381 protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input): void
384 $date = date_create($input);
385 $query->where('updated_at', '<', $date);
386 } catch (\Exception $e) {
390 protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input): void
393 $date = date_create($input);
394 $query->where('created_at', '>=', $date);
395 } catch (\Exception $e) {
399 protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
402 $date = date_create($input);
403 $query->where('created_at', '<', $date);
404 } catch (\Exception $e) {
408 protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
410 $userSlug = $input === 'me' ? user()->slug : trim($input);
411 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
413 $query->where('created_by', '=', $user->id);
417 protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
419 $userSlug = $input === 'me' ? user()->slug : trim($input);
420 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
422 $query->where('updated_by', '=', $user->id);
426 protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
428 $userSlug = $input === 'me' ? user()->slug : trim($input);
429 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
431 $query->where('owned_by', '=', $user->id);
435 protected function filterInName(EloquentBuilder $query, Entity $model, $input)
437 $query->where('name', 'like', '%' . $input . '%');
440 protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
442 $this->filterInName($query, $model, $input);
445 protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
447 $query->where($model->textField, 'like', '%' . $input . '%');
450 protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
452 $query->where('restricted', '=', true);
455 protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
457 $query->whereHas('views', function ($query) {
458 $query->where('user_id', '=', user()->id);
462 protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
464 $query->whereDoesntHave('views', function ($query) {
465 $query->where('user_id', '=', user()->id);
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');