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 can 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)) {
71 $search = $this->searchEntityTable($searchOpts, $entityType, $page, $count, $action);
72 $entityTotal = $this->searchEntityTable($searchOpts, $entityType, $page, $count, $action, true);
73 if ($entityTotal > $page * $count) {
76 $total += $entityTotal;
77 $results = $results->merge($search);
82 'count' => count($results),
83 'has_more' => $hasMore,
84 'results' => $results->sortByDesc('score')->values(),
89 * Search a book for entities.
91 public function searchBook(int $bookId, string $searchString): Collection
93 $opts = SearchOptions::fromString($searchString);
94 $entityTypes = ['page', 'chapter'];
95 $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
98 foreach ($entityTypesToSearch as $entityType) {
99 if (!in_array($entityType, $entityTypes)) {
102 $search = $this->buildEntitySearchQuery($opts, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
103 $results = $results->merge($search);
106 return $results->sortByDesc('score')->take(20);
110 * Search a chapter for entities.
112 public function searchChapter(int $chapterId, string $searchString): Collection
114 $opts = SearchOptions::fromString($searchString);
115 $pages = $this->buildEntitySearchQuery($opts, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
117 return $pages->sortByDesc('score');
121 * Search across a particular entity type.
122 * Setting getCount = true will return the total
123 * matching instead of the items themselves.
125 * @return \Illuminate\Database\Eloquent\Collection|int|static[]
127 protected function searchEntityTable(SearchOptions $searchOpts, string $entityType = 'page', int $page = 1, int $count = 20, string $action = 'view', bool $getCount = false)
129 $query = $this->buildEntitySearchQuery($searchOpts, $entityType, $action);
131 return $query->count();
134 $query = $query->skip(($page - 1) * $count)->take($count);
136 return $query->get();
140 * Create a search query for an entity.
142 protected function buildEntitySearchQuery(SearchOptions $searchOpts, string $entityType = 'page', string $action = 'view'): EloquentBuilder
144 $entity = $this->entityProvider->get($entityType);
145 $entitySelect = $entity->newQuery();
147 // Handle normal search terms
148 if (count($searchOpts->searches) > 0) {
149 $rawScoreSum = $this->db->raw('SUM(score) as score');
150 $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', $rawScoreSum);
151 $subQuery->where('entity_type', '=', $entity->getMorphClass());
152 $subQuery->where(function (Builder $query) use ($searchOpts) {
153 foreach ($searchOpts->searches as $inputTerm) {
154 $query->orWhere('term', 'like', $inputTerm . '%');
156 })->groupBy('entity_type', 'entity_id');
157 $entitySelect->join($this->db->raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) {
158 $join->on('id', '=', 'entity_id');
159 })->selectRaw($entity->getTable() . '.*, s.score')->orderBy('score', 'desc');
160 $entitySelect->mergeBindings($subQuery);
163 // Handle exact term matching
164 foreach ($searchOpts->exacts as $inputTerm) {
165 $entitySelect->where(function (EloquentBuilder $query) use ($inputTerm, $entity) {
166 $query->where('name', 'like', '%' . $inputTerm . '%')
167 ->orWhere($entity->textField, 'like', '%' . $inputTerm . '%');
171 // Handle tag searches
172 foreach ($searchOpts->tags as $inputTerm) {
173 $this->applyTagSearch($entitySelect, $inputTerm);
177 foreach ($searchOpts->filters as $filterTerm => $filterValue) {
178 $functionName = Str::camel('filter_' . $filterTerm);
179 if (method_exists($this, $functionName)) {
180 $this->$functionName($entitySelect, $entity, $filterValue);
184 return $this->permissionService->enforceEntityRestrictions($entity, $entitySelect, $action);
188 * Get the available query operators as a regex escaped list.
190 protected function getRegexEscapedOperators(): string
192 $escapedOperators = [];
193 foreach ($this->queryOperators as $operator) {
194 $escapedOperators[] = preg_quote($operator);
197 return join('|', $escapedOperators);
201 * Apply a tag search term onto a entity query.
203 protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
205 preg_match('/^(.*?)((' . $this->getRegexEscapedOperators() . ')(.*?))?$/', $tagTerm, $tagSplit);
206 $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
207 $tagName = $tagSplit[1];
208 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
209 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
210 $validOperator = in_array($tagOperator, $this->queryOperators);
211 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
212 if (!empty($tagName)) {
213 $query->where('name', '=', $tagName);
215 if (is_numeric($tagValue) && $tagOperator !== 'like') {
216 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
217 // search the value as a string which prevents being able to do number-based operations
218 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
219 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
220 $query->whereRaw("value ${tagOperator} ${tagValue}");
222 $query->where('value', $tagOperator, $tagValue);
225 $query->where('name', '=', $tagName);
233 * Custom entity search filters.
235 protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input)
238 $date = date_create($input);
239 } catch (\Exception $e) {
242 $query->where('updated_at', '>=', $date);
245 protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input)
248 $date = date_create($input);
249 } catch (\Exception $e) {
252 $query->where('updated_at', '<', $date);
255 protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input)
258 $date = date_create($input);
259 } catch (\Exception $e) {
262 $query->where('created_at', '>=', $date);
265 protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
268 $date = date_create($input);
269 } catch (\Exception $e) {
272 $query->where('created_at', '<', $date);
275 protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
277 $userSlug = $input === 'me' ? user()->slug : trim($input);
278 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
280 $query->where('created_by', '=', $user->id);
284 protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
286 $userSlug = $input === 'me' ? user()->slug : trim($input);
287 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
289 $query->where('updated_by', '=', $user->id);
293 protected function filterOwnedBy(EloquentBuilder $query, Entity $model, $input)
295 $userSlug = $input === 'me' ? user()->slug : trim($input);
296 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
298 $query->where('owned_by', '=', $user->id);
302 protected function filterInName(EloquentBuilder $query, Entity $model, $input)
304 $query->where('name', 'like', '%' . $input . '%');
307 protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
309 $this->filterInName($query, $model, $input);
312 protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
314 $query->where($model->textField, 'like', '%' . $input . '%');
317 protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
319 $query->where('restricted', '=', true);
322 protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
324 $query->whereHas('views', function ($query) {
325 $query->where('user_id', '=', user()->id);
329 protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
331 $query->whereDoesntHave('views', function ($query) {
332 $query->where('user_id', '=', user()->id);
336 protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
338 $functionName = Str::camel('sort_by_' . $input);
339 if (method_exists($this, $functionName)) {
340 $this->$functionName($query, $model);
345 * Sorting filter options.
347 protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
349 $commentsTable = $this->db->getTablePrefix() . 'comments';
350 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
351 $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');
353 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');