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 public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20, string $action = 'view'): array
62 $entityTypes = array_keys($this->entityProvider->all());
63 $entityTypesToSearch = $entityTypes;
65 if ($entityType !== 'all') {
66 $entityTypesToSearch = $entityType;
67 } elseif (isset($searchOpts->filters['type'])) {
68 $entityTypesToSearch = explode('|', $searchOpts->filters['type']);
75 foreach ($entityTypesToSearch as $entityType) {
76 if (!in_array($entityType, $entityTypes)) {
80 $entityModelInstance = $this->entityProvider->get($entityType);
81 $searchQuery = $this->buildQuery($searchOpts, $entityModelInstance, $action);
82 $entityTotal = $searchQuery->count();
83 $searchResults = $this->getPageOfDataFromQuery($searchQuery, $entityModelInstance, $page, $count);
85 if ($entityTotal > ($page * $count)) {
89 $total += $entityTotal;
90 $results = $results->merge($searchResults);
95 'count' => count($results),
96 'has_more' => $hasMore,
97 'results' => $results->sortByDesc('score')->values(),
102 * Search a book for entities.
104 public function searchBook(int $bookId, string $searchString): Collection
106 $opts = SearchOptions::fromString($searchString);
107 $entityTypes = ['page', 'chapter'];
108 $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
110 $results = collect();
111 foreach ($entityTypesToSearch as $entityType) {
112 if (!in_array($entityType, $entityTypes)) {
116 $entityModelInstance = $this->entityProvider->get($entityType);
117 $search = $this->buildQuery($opts, $entityModelInstance)->where('book_id', '=', $bookId)->take(20)->get();
118 $results = $results->merge($search);
121 return $results->sortByDesc('score')->take(20);
125 * Search a chapter for entities.
127 public function searchChapter(int $chapterId, string $searchString): Collection
129 $opts = SearchOptions::fromString($searchString);
130 $entityModelInstance = $this->entityProvider->get('page');
131 $pages = $this->buildQuery($opts, $entityModelInstance)->where('chapter_id', '=', $chapterId)->take(20)->get();
133 return $pages->sortByDesc('score');
137 * Get a page of result data from the given query based on the provided page parameters.
139 protected function getPageOfDataFromQuery(EloquentBuilder $query, Entity $entityModelInstance, int $page = 1, int $count = 20): EloquentCollection
141 $relations = ['tags'];
143 if ($entityModelInstance instanceof BookChild) {
144 $relations['book'] = function (BelongsTo $query) {
149 if ($entityModelInstance instanceof Page) {
150 $relations['chapter'] = function (BelongsTo $query) {
155 return $query->clone()
156 ->with(array_filter($relations))
157 ->skip(($page - 1) * $count)
163 * Create a search query for an entity.
165 protected function buildQuery(SearchOptions $searchOpts, Entity $entityModelInstance, string $action = 'view'): EloquentBuilder
167 $entityQuery = $entityModelInstance->newQuery();
169 if ($entityModelInstance instanceof Page) {
170 $entityQuery->select($entityModelInstance::$listAttributes);
172 $entityQuery->select(['*']);
175 // Handle normal search terms
176 $this->applyTermSearch($entityQuery, $searchOpts, $entityModelInstance);
178 // Handle exact term matching
179 foreach ($searchOpts->exacts as $inputTerm) {
180 $entityQuery->where(function (EloquentBuilder $query) use ($inputTerm, $entityModelInstance) {
181 $query->where('name', 'like', '%' . $inputTerm . '%')
182 ->orWhere($entityModelInstance->textField, 'like', '%' . $inputTerm . '%');
186 // Handle tag searches
187 foreach ($searchOpts->tags as $inputTerm) {
188 $this->applyTagSearch($entityQuery, $inputTerm);
192 foreach ($searchOpts->filters as $filterTerm => $filterValue) {
193 $functionName = Str::camel('filter_' . $filterTerm);
194 if (method_exists($this, $functionName)) {
195 $this->$functionName($entityQuery, $entityModelInstance, $filterValue);
199 return $this->permissionService->enforceEntityRestrictions($entityModelInstance, $entityQuery, $action);
203 * For the given search query, apply the queries for handling the regular search terms.
205 protected function applyTermSearch(EloquentBuilder $entityQuery, SearchOptions $options, Entity $entity): void
207 $terms = $options->searches;
208 if (count($terms) === 0) {
212 $scoredTerms = $this->getTermAdjustments($options);
213 $scoreSelect = $this->selectForScoredTerms($scoredTerms);
215 $subQuery = DB::table('search_terms')->select([
218 DB::raw($scoreSelect['statement']),
221 $subQuery->addBinding($scoreSelect['bindings'], 'select');
223 $subQuery->where('entity_type', '=', $entity->getMorphClass());
224 $subQuery->where(function (Builder $query) use ($terms) {
225 foreach ($terms as $inputTerm) {
226 $query->orWhere('term', 'like', $inputTerm . '%');
229 $subQuery->groupBy('entity_type', 'entity_id');
231 $entityQuery->joinSub($subQuery, 's', 'id', '=', 'entity_id');
232 $entityQuery->addSelect('s.score');
233 $entityQuery->orderBy('score', 'desc');
237 * Create a select statement, with prepared bindings, for the given
238 * set of scored search terms.
240 * @param array<string, float> $scoredTerms
242 * @return array{statement: string, bindings: string[]}
244 protected function selectForScoredTerms(array $scoredTerms): array
246 // Within this we walk backwards to create the chain of 'if' statements
247 // so that each previous statement is used in the 'else' condition of
248 // the next (earlier) to be built. We start at '0' to have no score
249 // on no match (Should never actually get to this case).
252 foreach ($scoredTerms as $term => $score) {
253 $ifChain = 'IF(term like ?, score * ' . (float) $score . ', ' . $ifChain . ')';
254 $bindings[] = $term . '%';
258 'statement' => 'SUM(' . $ifChain . ') as score',
259 'bindings' => array_reverse($bindings),
264 * For the terms in the given search options, query their popularity across all
265 * search terms then provide that back as score adjustment multiplier applicable
266 * for their rarity. Returns an array of float multipliers, keyed by term.
268 * @return array<string, float>
270 protected function getTermAdjustments(SearchOptions $options): array
272 if (isset($this->termAdjustmentCache[$options])) {
273 return $this->termAdjustmentCache[$options];
276 $termQuery = SearchTerm::query()->toBase();
277 $whenStatements = [];
280 foreach ($options->searches as $term) {
281 $whenStatements[] = 'WHEN term LIKE ? THEN ?';
282 $whenBindings[] = $term . '%';
283 $whenBindings[] = $term;
285 $termQuery->orWhere('term', 'like', $term . '%');
288 $case = 'CASE ' . implode(' ', $whenStatements) . ' END';
289 $termQuery->selectRaw($case . ' as term', $whenBindings);
290 $termQuery->selectRaw('COUNT(*) as count');
291 $termQuery->groupByRaw($case, $whenBindings);
293 $termCounts = $termQuery->pluck('count', 'term')->toArray();
294 $adjusted = $this->rawTermCountsToAdjustments($termCounts);
296 $this->termAdjustmentCache[$options] = $adjusted;
298 return $this->termAdjustmentCache[$options];
302 * Convert counts of terms into a relative-count normalised multiplier.
304 * @param array<string, int> $termCounts
306 * @return array<string, int>
308 protected function rawTermCountsToAdjustments(array $termCounts): array
310 if (empty($termCounts)) {
315 $max = max(array_values($termCounts));
317 foreach ($termCounts as $term => $count) {
318 $percent = round($count / $max, 5);
319 $multipliers[$term] = 1.3 - $percent;
326 * Get the available query operators as a regex escaped list.
328 protected function getRegexEscapedOperators(): string
330 $escapedOperators = [];
331 foreach ($this->queryOperators as $operator) {
332 $escapedOperators[] = preg_quote($operator);
335 return implode('|', $escapedOperators);
339 * Apply a tag search term onto a entity query.
341 protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
343 preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit);
344 $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
345 $tagName = $tagSplit[1];
346 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
347 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
348 $validOperator = in_array($tagOperator, $this->queryOperators);
349 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
350 if (!empty($tagName)) {
351 $query->where('name', '=', $tagName);
353 if (is_numeric($tagValue) && $tagOperator !== 'like') {
354 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
355 // search the value as a string which prevents being able to do number-based operations
356 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
357 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
358 $query->whereRaw("value ${tagOperator} ${tagValue}");
360 $query->where('value', $tagOperator, $tagValue);
363 $query->where('name', '=', $tagName);
371 * Custom entity search filters.
373 protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input): void
376 $date = date_create($input);
377 $query->where('updated_at', '>=', $date);
378 } catch (\Exception $e) {
382 protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input): void
385 $date = date_create($input);
386 $query->where('updated_at', '<', $date);
387 } catch (\Exception $e) {
391 protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input): void
394 $date = date_create($input);
395 $query->where('created_at', '>=', $date);
396 } catch (\Exception $e) {
400 protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
403 $date = date_create($input);
404 $query->where('created_at', '<', $date);
405 } catch (\Exception $e) {
409 protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
411 $userSlug = $input === 'me' ? user()->slug : trim($input);
412 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
414 $query->where('created_by', '=', $user->id);
418 protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
420 $userSlug = $input === 'me' ? user()->slug : trim($input);
421 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
423 $query->where('updated_by', '=', $user->id);
427 protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
429 $userSlug = $input === 'me' ? user()->slug : trim($input);
430 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
432 $query->where('owned_by', '=', $user->id);
436 protected function filterInName(EloquentBuilder $query, Entity $model, $input)
438 $query->where('name', 'like', '%' . $input . '%');
441 protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
443 $this->filterInName($query, $model, $input);
446 protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
448 $query->where($model->textField, 'like', '%' . $input . '%');
451 protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
453 $query->where('restricted', '=', true);
456 protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
458 $query->whereHas('views', function ($query) {
459 $query->where('user_id', '=', user()->id);
463 protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
465 $query->whereDoesntHave('views', function ($query) {
466 $query->where('user_id', '=', user()->id);
470 protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
472 $functionName = Str::camel('sort_by_' . $input);
473 if (method_exists($this, $functionName)) {
474 $this->$functionName($query, $model);
479 * Sorting filter options.
481 protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
483 $commentsTable = DB::getTablePrefix() . 'comments';
484 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
485 $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');
487 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');