3 namespace BookStack\Entities\Tools;
5 use BookStack\Auth\Permissions\PermissionService;
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;
27 protected $entityProvider;
30 * @var PermissionService
32 protected $permissionService;
35 * Acceptable operators to be used in a query.
39 protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
42 * Retain a cache of score adjusted terms for specific search options.
43 * From PHP>=8 this can be made into a WeakMap instead.
45 * @var SplObjectStorage
47 protected $termAdjustmentCache;
49 public function __construct(EntityProvider $entityProvider, PermissionService $permissionService)
51 $this->entityProvider = $entityProvider;
52 $this->permissionService = $permissionService;
53 $this->termAdjustmentCache = new SplObjectStorage();
57 * Search all entities in the system.
58 * The provided count is for each entity to search,
59 * Total returned could be larger and not guaranteed.
61 * @return array{total: int, count: int, has_more: bool, results: Entity[]}
63 public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20, string $action = 'view'): array
65 $entityTypes = array_keys($this->entityProvider->all());
66 $entityTypesToSearch = $entityTypes;
68 if ($entityType !== 'all') {
69 $entityTypesToSearch = $entityType;
70 } elseif (isset($searchOpts->filters['type'])) {
71 $entityTypesToSearch = explode('|', $searchOpts->filters['type']);
78 foreach ($entityTypesToSearch as $entityType) {
79 if (!in_array($entityType, $entityTypes)) {
83 $entityModelInstance = $this->entityProvider->get($entityType);
84 $searchQuery = $this->buildQuery($searchOpts, $entityModelInstance, $action);
85 $entityTotal = $searchQuery->count();
86 $searchResults = $this->getPageOfDataFromQuery($searchQuery, $entityModelInstance, $page, $count);
88 if ($entityTotal > ($page * $count)) {
92 $total += $entityTotal;
93 $results = $results->merge($searchResults);
98 'count' => count($results),
99 'has_more' => $hasMore,
100 'results' => $results->sortByDesc('score')->values(),
105 * Search a book for entities.
107 public function searchBook(int $bookId, string $searchString): Collection
109 $opts = SearchOptions::fromString($searchString);
110 $entityTypes = ['page', 'chapter'];
111 $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
113 $results = collect();
114 foreach ($entityTypesToSearch as $entityType) {
115 if (!in_array($entityType, $entityTypes)) {
119 $entityModelInstance = $this->entityProvider->get($entityType);
120 $search = $this->buildQuery($opts, $entityModelInstance)->where('book_id', '=', $bookId)->take(20)->get();
121 $results = $results->merge($search);
124 return $results->sortByDesc('score')->take(20);
128 * Search a chapter for entities.
130 public function searchChapter(int $chapterId, string $searchString): Collection
132 $opts = SearchOptions::fromString($searchString);
133 $entityModelInstance = $this->entityProvider->get('page');
134 $pages = $this->buildQuery($opts, $entityModelInstance)->where('chapter_id', '=', $chapterId)->take(20)->get();
136 return $pages->sortByDesc('score');
140 * Get a page of result data from the given query based on the provided page parameters.
142 protected function getPageOfDataFromQuery(EloquentBuilder $query, Entity $entityModelInstance, int $page = 1, int $count = 20): EloquentCollection
144 $relations = ['tags'];
146 if ($entityModelInstance instanceof BookChild) {
147 $relations['book'] = function (BelongsTo $query) {
148 $query->scopes('visible');
152 if ($entityModelInstance instanceof Page) {
153 $relations['chapter'] = function (BelongsTo $query) {
154 $query->scopes('visible');
158 return $query->clone()
159 ->with(array_filter($relations))
160 ->skip(($page - 1) * $count)
166 * Create a search query for an entity.
168 protected function buildQuery(SearchOptions $searchOpts, Entity $entityModelInstance, string $action = 'view'): EloquentBuilder
170 $entityQuery = $entityModelInstance->newQuery();
172 if ($entityModelInstance instanceof Page) {
173 $entityQuery->select($entityModelInstance::$listAttributes);
175 $entityQuery->select(['*']);
178 // Handle normal search terms
179 $this->applyTermSearch($entityQuery, $searchOpts, $entityModelInstance);
181 // Handle exact term matching
182 foreach ($searchOpts->exacts as $inputTerm) {
183 $entityQuery->where(function (EloquentBuilder $query) use ($inputTerm, $entityModelInstance) {
184 $query->where('name', 'like', '%' . $inputTerm . '%')
185 ->orWhere($entityModelInstance->textField, 'like', '%' . $inputTerm . '%');
189 // Handle tag searches
190 foreach ($searchOpts->tags as $inputTerm) {
191 $this->applyTagSearch($entityQuery, $inputTerm);
195 foreach ($searchOpts->filters as $filterTerm => $filterValue) {
196 $functionName = Str::camel('filter_' . $filterTerm);
197 if (method_exists($this, $functionName)) {
198 $this->$functionName($entityQuery, $entityModelInstance, $filterValue);
202 return $this->permissionService->enforceEntityRestrictions($entityModelInstance, $entityQuery, $action);
206 * For the given search query, apply the queries for handling the regular search terms.
208 protected function applyTermSearch(EloquentBuilder $entityQuery, SearchOptions $options, Entity $entity): void
210 $terms = $options->searches;
211 if (count($terms) === 0) {
215 $scoredTerms = $this->getTermAdjustments($options);
216 $scoreSelect = $this->selectForScoredTerms($scoredTerms);
218 $subQuery = DB::table('search_terms')->select([
221 DB::raw($scoreSelect['statement']),
224 $subQuery->addBinding($scoreSelect['bindings'], 'select');
226 $subQuery->where('entity_type', '=', $entity->getMorphClass());
227 $subQuery->where(function (Builder $query) use ($terms) {
228 foreach ($terms as $inputTerm) {
229 $query->orWhere('term', 'like', $inputTerm . '%');
232 $subQuery->groupBy('entity_type', 'entity_id');
234 $entityQuery->joinSub($subQuery, 's', 'id', '=', 'entity_id');
235 $entityQuery->addSelect('s.score');
236 $entityQuery->orderBy('score', 'desc');
240 * Create a select statement, with prepared bindings, for the given
241 * set of scored search terms.
243 * @param array<string, float> $scoredTerms
245 * @return array{statement: string, bindings: string[]}
247 protected function selectForScoredTerms(array $scoredTerms): array
249 // Within this we walk backwards to create the chain of 'if' statements
250 // so that each previous statement is used in the 'else' condition of
251 // the next (earlier) to be built. We start at '0' to have no score
252 // on no match (Should never actually get to this case).
255 foreach ($scoredTerms as $term => $score) {
256 $ifChain = 'IF(term like ?, score * ' . (float) $score . ', ' . $ifChain . ')';
257 $bindings[] = $term . '%';
261 'statement' => 'SUM(' . $ifChain . ') as score',
262 'bindings' => array_reverse($bindings),
267 * For the terms in the given search options, query their popularity across all
268 * search terms then provide that back as score adjustment multiplier applicable
269 * for their rarity. Returns an array of float multipliers, keyed by term.
271 * @return array<string, float>
273 protected function getTermAdjustments(SearchOptions $options): array
275 if (isset($this->termAdjustmentCache[$options])) {
276 return $this->termAdjustmentCache[$options];
279 $termQuery = SearchTerm::query()->toBase();
280 $whenStatements = [];
283 foreach ($options->searches as $term) {
284 $whenStatements[] = 'WHEN term LIKE ? THEN ?';
285 $whenBindings[] = $term . '%';
286 $whenBindings[] = $term;
288 $termQuery->orWhere('term', 'like', $term . '%');
291 $case = 'CASE ' . implode(' ', $whenStatements) . ' END';
292 $termQuery->selectRaw($case . ' as term', $whenBindings);
293 $termQuery->selectRaw('COUNT(*) as count');
294 $termQuery->groupByRaw($case, $whenBindings);
296 $termCounts = $termQuery->pluck('count', 'term')->toArray();
297 $adjusted = $this->rawTermCountsToAdjustments($termCounts);
299 $this->termAdjustmentCache[$options] = $adjusted;
301 return $this->termAdjustmentCache[$options];
305 * Convert counts of terms into a relative-count normalised multiplier.
307 * @param array<string, int> $termCounts
309 * @return array<string, int>
311 protected function rawTermCountsToAdjustments(array $termCounts): array
313 if (empty($termCounts)) {
318 $max = max(array_values($termCounts));
320 foreach ($termCounts as $term => $count) {
321 $percent = round($count / $max, 5);
322 $multipliers[$term] = 1.3 - $percent;
329 * Get the available query operators as a regex escaped list.
331 protected function getRegexEscapedOperators(): string
333 $escapedOperators = [];
334 foreach ($this->queryOperators as $operator) {
335 $escapedOperators[] = preg_quote($operator);
338 return implode('|', $escapedOperators);
342 * Apply a tag search term onto a entity query.
344 protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
346 preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit);
347 $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
348 $tagName = $tagSplit[1];
349 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
350 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
351 $validOperator = in_array($tagOperator, $this->queryOperators);
352 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
353 if (!empty($tagName)) {
354 $query->where('name', '=', $tagName);
356 if (is_numeric($tagValue) && $tagOperator !== 'like') {
357 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
358 // search the value as a string which prevents being able to do number-based operations
359 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
360 /** @var Connection $connection */
361 $connection = $query->getConnection();
362 $tagValue = (float) trim($connection->getPdo()->quote($tagValue), "'");
363 $query->whereRaw("value {$tagOperator} {$tagValue}");
365 $query->where('value', $tagOperator, $tagValue);
368 $query->where('name', '=', $tagName);
376 * Custom entity search filters.
378 protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input): void
381 $date = date_create($input);
382 $query->where('updated_at', '>=', $date);
383 } catch (\Exception $e) {
387 protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input): void
390 $date = date_create($input);
391 $query->where('updated_at', '<', $date);
392 } catch (\Exception $e) {
396 protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input): void
399 $date = date_create($input);
400 $query->where('created_at', '>=', $date);
401 } catch (\Exception $e) {
405 protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
408 $date = date_create($input);
409 $query->where('created_at', '<', $date);
410 } catch (\Exception $e) {
414 protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
416 $userSlug = $input === 'me' ? user()->slug : trim($input);
417 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
419 $query->where('created_by', '=', $user->id);
423 protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
425 $userSlug = $input === 'me' ? user()->slug : trim($input);
426 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
428 $query->where('updated_by', '=', $user->id);
432 protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
434 $userSlug = $input === 'me' ? user()->slug : trim($input);
435 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
437 $query->where('owned_by', '=', $user->id);
441 protected function filterInName(EloquentBuilder $query, Entity $model, $input)
443 $query->where('name', 'like', '%' . $input . '%');
446 protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
448 $this->filterInName($query, $model, $input);
451 protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
453 $query->where($model->textField, 'like', '%' . $input . '%');
456 protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
458 $query->where('restricted', '=', true);
461 protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
463 $query->whereHas('views', function ($query) {
464 $query->where('user_id', '=', user()->id);
468 protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
470 $query->whereDoesntHave('views', function ($query) {
471 $query->where('user_id', '=', user()->id);
475 protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
477 $functionName = Str::camel('sort_by_' . $input);
478 if (method_exists($this, $functionName)) {
479 $this->$functionName($query, $model);
484 * Sorting filter options.
486 protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
488 $commentsTable = DB::getTablePrefix() . 'comments';
489 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
490 $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');
492 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');