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\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;
26 protected $entityProvider;
29 * @var PermissionService
31 protected $permissionService;
34 * Acceptable operators to be used in a query.
38 protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
41 * Retain a cache of score adjusted terms for specific search options.
42 * From PHP>=8 this can be made into a WeakMap instead.
44 * @var SplObjectStorage
46 protected $termAdjustmentCache;
48 public function __construct(EntityProvider $entityProvider, PermissionService $permissionService)
50 $this->entityProvider = $entityProvider;
51 $this->permissionService = $permissionService;
52 $this->termAdjustmentCache = new SplObjectStorage();
56 * Search all entities in the system.
57 * The provided count is for each entity to search,
58 * Total returned could be larger and not guaranteed.
60 * @return array{total: int, count: int, has_more: bool, results: Entity[]}
62 public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20, string $action = 'view'): array
64 $entityTypes = array_keys($this->entityProvider->all());
65 $entityTypesToSearch = $entityTypes;
67 if ($entityType !== 'all') {
68 $entityTypesToSearch = $entityType;
69 } elseif (isset($searchOpts->filters['type'])) {
70 $entityTypesToSearch = explode('|', $searchOpts->filters['type']);
77 foreach ($entityTypesToSearch as $entityType) {
78 if (!in_array($entityType, $entityTypes)) {
82 $entityModelInstance = $this->entityProvider->get($entityType);
83 $searchQuery = $this->buildQuery($searchOpts, $entityModelInstance, $action);
84 $entityTotal = $searchQuery->count();
85 $searchResults = $this->getPageOfDataFromQuery($searchQuery, $entityModelInstance, $page, $count);
87 if ($entityTotal > ($page * $count)) {
91 $total += $entityTotal;
92 $results = $results->merge($searchResults);
97 'count' => count($results),
98 'has_more' => $hasMore,
99 'results' => $results->sortByDesc('score')->values(),
104 * Search a book for entities.
106 public function searchBook(int $bookId, string $searchString): Collection
108 $opts = SearchOptions::fromString($searchString);
109 $entityTypes = ['page', 'chapter'];
110 $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
112 $results = collect();
113 foreach ($entityTypesToSearch as $entityType) {
114 if (!in_array($entityType, $entityTypes)) {
118 $entityModelInstance = $this->entityProvider->get($entityType);
119 $search = $this->buildQuery($opts, $entityModelInstance)->where('book_id', '=', $bookId)->take(20)->get();
120 $results = $results->merge($search);
123 return $results->sortByDesc('score')->take(20);
127 * Search a chapter for entities.
129 public function searchChapter(int $chapterId, string $searchString): Collection
131 $opts = SearchOptions::fromString($searchString);
132 $entityModelInstance = $this->entityProvider->get('page');
133 $pages = $this->buildQuery($opts, $entityModelInstance)->where('chapter_id', '=', $chapterId)->take(20)->get();
135 return $pages->sortByDesc('score');
139 * Get a page of result data from the given query based on the provided page parameters.
141 protected function getPageOfDataFromQuery(EloquentBuilder $query, Entity $entityModelInstance, int $page = 1, int $count = 20): EloquentCollection
143 $relations = ['tags'];
145 if ($entityModelInstance instanceof BookChild) {
146 $relations['book'] = function (BelongsTo $query) {
151 if ($entityModelInstance instanceof Page) {
152 $relations['chapter'] = function (BelongsTo $query) {
157 return $query->clone()
158 ->with(array_filter($relations))
159 ->skip(($page - 1) * $count)
165 * Create a search query for an entity.
167 protected function buildQuery(SearchOptions $searchOpts, Entity $entityModelInstance, string $action = 'view'): EloquentBuilder
169 $entityQuery = $entityModelInstance->newQuery();
171 if ($entityModelInstance instanceof Page) {
172 $entityQuery->select($entityModelInstance::$listAttributes);
174 $entityQuery->select(['*']);
177 // Handle normal search terms
178 $this->applyTermSearch($entityQuery, $searchOpts, $entityModelInstance);
180 // Handle exact term matching
181 foreach ($searchOpts->exacts as $inputTerm) {
182 $entityQuery->where(function (EloquentBuilder $query) use ($inputTerm, $entityModelInstance) {
183 $query->where('name', 'like', '%' . $inputTerm . '%')
184 ->orWhere($entityModelInstance->textField, 'like', '%' . $inputTerm . '%');
188 // Handle tag searches
189 foreach ($searchOpts->tags as $inputTerm) {
190 $this->applyTagSearch($entityQuery, $inputTerm);
194 foreach ($searchOpts->filters as $filterTerm => $filterValue) {
195 $functionName = Str::camel('filter_' . $filterTerm);
196 if (method_exists($this, $functionName)) {
197 $this->$functionName($entityQuery, $entityModelInstance, $filterValue);
201 return $this->permissionService->enforceEntityRestrictions($entityModelInstance, $entityQuery, $action);
205 * For the given search query, apply the queries for handling the regular search terms.
207 protected function applyTermSearch(EloquentBuilder $entityQuery, SearchOptions $options, Entity $entity): void
209 $terms = $options->searches;
210 if (count($terms) === 0) {
214 $scoredTerms = $this->getTermAdjustments($options);
215 $scoreSelect = $this->selectForScoredTerms($scoredTerms);
217 $subQuery = DB::table('search_terms')->select([
220 DB::raw($scoreSelect['statement']),
223 $subQuery->addBinding($scoreSelect['bindings'], 'select');
225 $subQuery->where('entity_type', '=', $entity->getMorphClass());
226 $subQuery->where(function (Builder $query) use ($terms) {
227 foreach ($terms as $inputTerm) {
228 $query->orWhere('term', 'like', $inputTerm . '%');
231 $subQuery->groupBy('entity_type', 'entity_id');
233 $entityQuery->joinSub($subQuery, 's', 'id', '=', 'entity_id');
234 $entityQuery->addSelect('s.score');
235 $entityQuery->orderBy('score', 'desc');
239 * Create a select statement, with prepared bindings, for the given
240 * set of scored search terms.
242 * @param array<string, float> $scoredTerms
244 * @return array{statement: string, bindings: string[]}
246 protected function selectForScoredTerms(array $scoredTerms): array
248 // Within this we walk backwards to create the chain of 'if' statements
249 // so that each previous statement is used in the 'else' condition of
250 // the next (earlier) to be built. We start at '0' to have no score
251 // on no match (Should never actually get to this case).
254 foreach ($scoredTerms as $term => $score) {
255 $ifChain = 'IF(term like ?, score * ' . (float) $score . ', ' . $ifChain . ')';
256 $bindings[] = $term . '%';
260 'statement' => 'SUM(' . $ifChain . ') as score',
261 'bindings' => array_reverse($bindings),
266 * For the terms in the given search options, query their popularity across all
267 * search terms then provide that back as score adjustment multiplier applicable
268 * for their rarity. Returns an array of float multipliers, keyed by term.
270 * @return array<string, float>
272 protected function getTermAdjustments(SearchOptions $options): array
274 if (isset($this->termAdjustmentCache[$options])) {
275 return $this->termAdjustmentCache[$options];
278 $termQuery = SearchTerm::query()->toBase();
279 $whenStatements = [];
282 foreach ($options->searches as $term) {
283 $whenStatements[] = 'WHEN term LIKE ? THEN ?';
284 $whenBindings[] = $term . '%';
285 $whenBindings[] = $term;
287 $termQuery->orWhere('term', 'like', $term . '%');
290 $case = 'CASE ' . implode(' ', $whenStatements) . ' END';
291 $termQuery->selectRaw($case . ' as term', $whenBindings);
292 $termQuery->selectRaw('COUNT(*) as count');
293 $termQuery->groupByRaw($case, $whenBindings);
295 $termCounts = $termQuery->pluck('count', 'term')->toArray();
296 $adjusted = $this->rawTermCountsToAdjustments($termCounts);
298 $this->termAdjustmentCache[$options] = $adjusted;
300 return $this->termAdjustmentCache[$options];
304 * Convert counts of terms into a relative-count normalised multiplier.
306 * @param array<string, int> $termCounts
308 * @return array<string, int>
310 protected function rawTermCountsToAdjustments(array $termCounts): array
312 if (empty($termCounts)) {
317 $max = max(array_values($termCounts));
319 foreach ($termCounts as $term => $count) {
320 $percent = round($count / $max, 5);
321 $multipliers[$term] = 1.3 - $percent;
328 * Get the available query operators as a regex escaped list.
330 protected function getRegexEscapedOperators(): string
332 $escapedOperators = [];
333 foreach ($this->queryOperators as $operator) {
334 $escapedOperators[] = preg_quote($operator);
337 return implode('|', $escapedOperators);
341 * Apply a tag search term onto a entity query.
343 protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
345 preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit);
346 $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
347 $tagName = $tagSplit[1];
348 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
349 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
350 $validOperator = in_array($tagOperator, $this->queryOperators);
351 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
352 if (!empty($tagName)) {
353 $query->where('name', '=', $tagName);
355 if (is_numeric($tagValue) && $tagOperator !== 'like') {
356 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
357 // search the value as a string which prevents being able to do number-based operations
358 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
359 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
360 $query->whereRaw("value ${tagOperator} ${tagValue}");
362 $query->where('value', $tagOperator, $tagValue);
365 $query->where('name', '=', $tagName);
373 * Custom entity search filters.
375 protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input): void
378 $date = date_create($input);
379 $query->where('updated_at', '>=', $date);
380 } catch (\Exception $e) {
384 protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input): void
387 $date = date_create($input);
388 $query->where('updated_at', '<', $date);
389 } catch (\Exception $e) {
393 protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input): void
396 $date = date_create($input);
397 $query->where('created_at', '>=', $date);
398 } catch (\Exception $e) {
402 protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
405 $date = date_create($input);
406 $query->where('created_at', '<', $date);
407 } catch (\Exception $e) {
411 protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
413 $userSlug = $input === 'me' ? user()->slug : trim($input);
414 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
416 $query->where('created_by', '=', $user->id);
420 protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
422 $userSlug = $input === 'me' ? user()->slug : trim($input);
423 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
425 $query->where('updated_by', '=', $user->id);
429 protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
431 $userSlug = $input === 'me' ? user()->slug : trim($input);
432 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
434 $query->where('owned_by', '=', $user->id);
438 protected function filterInName(EloquentBuilder $query, Entity $model, $input)
440 $query->where('name', 'like', '%' . $input . '%');
443 protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
445 $this->filterInName($query, $model, $input);
448 protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
450 $query->where($model->textField, 'like', '%' . $input . '%');
453 protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
455 $query->where('restricted', '=', true);
458 protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
460 $query->whereHas('views', function ($query) {
461 $query->where('user_id', '=', user()->id);
465 protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
467 $query->whereDoesntHave('views', function ($query) {
468 $query->where('user_id', '=', user()->id);
472 protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
474 $functionName = Str::camel('sort_by_' . $input);
475 if (method_exists($this, $functionName)) {
476 $this->$functionName($query, $model);
481 * Sorting filter options.
483 protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
485 $commentsTable = DB::getTablePrefix() . 'comments';
486 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
487 $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');
489 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');