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\Entity;
9 use Illuminate\Database\Connection;
10 use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
11 use Illuminate\Database\Query\Builder;
12 use Illuminate\Database\Query\JoinClause;
13 use Illuminate\Support\Collection;
14 use Illuminate\Support\Str;
21 protected $entityProvider;
29 * @var PermissionService
31 protected $permissionService;
34 * Acceptable operators to be used in a query.
38 protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
40 public function __construct(EntityProvider $entityProvider, Connection $db, PermissionService $permissionService)
42 $this->entityProvider = $entityProvider;
44 $this->permissionService = $permissionService;
48 * Search all entities in the system.
49 * The provided count is for each entity to search,
50 * Total returned could be larger and not guaranteed.
52 public function searchEntities(SearchOptions $searchOpts, string $entityType = 'all', int $page = 1, int $count = 20, string $action = 'view'): array
54 $entityTypes = array_keys($this->entityProvider->all());
55 $entityTypesToSearch = $entityTypes;
57 if ($entityType !== 'all') {
58 $entityTypesToSearch = $entityType;
59 } elseif (isset($searchOpts->filters['type'])) {
60 $entityTypesToSearch = explode('|', $searchOpts->filters['type']);
67 foreach ($entityTypesToSearch as $entityType) {
68 if (!in_array($entityType, $entityTypes)) {
72 $search = $this->searchEntityTable($searchOpts, $entityType, $page, $count, $action);
73 /** @var int $entityTotal */
74 $entityTotal = $this->searchEntityTable($searchOpts, $entityType, $page, $count, $action, true);
76 if ($entityTotal > ($page * $count)) {
80 $total += $entityTotal;
81 $results = $results->merge($search);
86 'count' => count($results),
87 'has_more' => $hasMore,
88 'results' => $results->sortByDesc('score')->values(),
93 * Search a book for entities.
95 public function searchBook(int $bookId, string $searchString): Collection
97 $opts = SearchOptions::fromString($searchString);
98 $entityTypes = ['page', 'chapter'];
99 $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
101 $results = collect();
102 foreach ($entityTypesToSearch as $entityType) {
103 if (!in_array($entityType, $entityTypes)) {
106 $search = $this->buildEntitySearchQuery($opts, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
107 $results = $results->merge($search);
110 return $results->sortByDesc('score')->take(20);
114 * Search a chapter for entities.
116 public function searchChapter(int $chapterId, string $searchString): Collection
118 $opts = SearchOptions::fromString($searchString);
119 $pages = $this->buildEntitySearchQuery($opts, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
121 return $pages->sortByDesc('score');
125 * Search across a particular entity type.
126 * Setting getCount = true will return the total
127 * matching instead of the items themselves.
129 * @return \Illuminate\Database\Eloquent\Collection|int|static[]
131 protected function searchEntityTable(SearchOptions $searchOpts, string $entityType = 'page', int $page = 1, int $count = 20, string $action = 'view', bool $getCount = false)
133 $query = $this->buildEntitySearchQuery($searchOpts, $entityType, $action);
135 return $query->count();
138 $query = $query->skip(($page - 1) * $count)->take($count);
140 return $query->get();
144 * Create a search query for an entity.
146 protected function buildEntitySearchQuery(SearchOptions $searchOpts, string $entityType = 'page', string $action = 'view'): EloquentBuilder
148 $entity = $this->entityProvider->get($entityType);
149 $entitySelect = $entity->newQuery();
151 // Handle normal search terms
152 if (count($searchOpts->searches) > 0) {
153 $rawScoreSum = $this->db->raw('SUM(score) as score');
154 $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', $rawScoreSum);
155 $subQuery->where('entity_type', '=', $entity->getMorphClass());
156 $subQuery->where(function (Builder $query) use ($searchOpts) {
157 foreach ($searchOpts->searches as $inputTerm) {
158 $query->orWhere('term', 'like', $inputTerm . '%');
160 })->groupBy('entity_type', 'entity_id');
161 $entitySelect->join($this->db->raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) {
162 $join->on('id', '=', 'entity_id');
163 })->addSelect($entity->getTable() . '.*')
164 ->selectRaw('s.score')
165 ->orderBy('score', 'desc');
166 $entitySelect->mergeBindings($subQuery);
169 // Handle exact term matching
170 foreach ($searchOpts->exacts as $inputTerm) {
171 $entitySelect->where(function (EloquentBuilder $query) use ($inputTerm, $entity) {
172 $query->where('name', 'like', '%' . $inputTerm . '%')
173 ->orWhere($entity->textField, 'like', '%' . $inputTerm . '%');
177 // Handle tag searches
178 foreach ($searchOpts->tags as $inputTerm) {
179 $this->applyTagSearch($entitySelect, $inputTerm);
183 foreach ($searchOpts->filters as $filterTerm => $filterValue) {
184 $functionName = Str::camel('filter_' . $filterTerm);
185 if (method_exists($this, $functionName)) {
186 $this->$functionName($entitySelect, $entity, $filterValue);
190 return $this->permissionService->enforceEntityRestrictions($entity, $entitySelect, $action);
194 * Get the available query operators as a regex escaped list.
196 protected function getRegexEscapedOperators(): string
198 $escapedOperators = [];
199 foreach ($this->queryOperators as $operator) {
200 $escapedOperators[] = preg_quote($operator);
203 return implode('|', $escapedOperators);
207 * Apply a tag search term onto a entity query.
209 protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
211 preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit);
212 $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
213 $tagName = $tagSplit[1];
214 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
215 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
216 $validOperator = in_array($tagOperator, $this->queryOperators);
217 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
218 if (!empty($tagName)) {
219 $query->where('name', '=', $tagName);
221 if (is_numeric($tagValue) && $tagOperator !== 'like') {
222 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
223 // search the value as a string which prevents being able to do number-based operations
224 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
225 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
226 $query->whereRaw("value ${tagOperator} ${tagValue}");
228 $query->where('value', $tagOperator, $tagValue);
231 $query->where('name', '=', $tagName);
239 * Custom entity search filters.
241 protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input)
244 $date = date_create($input);
245 } catch (\Exception $e) {
248 $query->where('updated_at', '>=', $date);
251 protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input)
254 $date = date_create($input);
255 } catch (\Exception $e) {
258 $query->where('updated_at', '<', $date);
261 protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input)
264 $date = date_create($input);
265 } catch (\Exception $e) {
268 $query->where('created_at', '>=', $date);
271 protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
274 $date = date_create($input);
275 } catch (\Exception $e) {
278 $query->where('created_at', '<', $date);
281 protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
283 $userSlug = $input === 'me' ? user()->slug : trim($input);
284 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
286 $query->where('created_by', '=', $user->id);
290 protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
292 $userSlug = $input === 'me' ? user()->slug : trim($input);
293 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
295 $query->where('updated_by', '=', $user->id);
299 protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
301 $userSlug = $input === 'me' ? user()->slug : trim($input);
302 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
304 $query->where('owned_by', '=', $user->id);
308 protected function filterInName(EloquentBuilder $query, Entity $model, $input)
310 $query->where('name', 'like', '%' . $input . '%');
313 protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
315 $this->filterInName($query, $model, $input);
318 protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
320 $query->where($model->textField, 'like', '%' . $input . '%');
323 protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
325 $query->where('restricted', '=', true);
328 protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
330 $query->whereHas('views', function ($query) {
331 $query->where('user_id', '=', user()->id);
335 protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
337 $query->whereDoesntHave('views', function ($query) {
338 $query->where('user_id', '=', user()->id);
342 protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
344 $functionName = Str::camel('sort_by_' . $input);
345 if (method_exists($this, $functionName)) {
346 $this->$functionName($query, $model);
351 * Sorting filter options.
353 protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
355 $commentsTable = $this->db->getTablePrefix() . 'comments';
356 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
357 $commentQuery = $this->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');
359 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');