1 <?php namespace BookStack\Entities\Tools;
3 use BookStack\Auth\Permissions\PermissionService;
4 use BookStack\Auth\User;
5 use BookStack\Entities\EntityProvider;
6 use BookStack\Entities\Models\Entity;
7 use Illuminate\Database\Connection;
8 use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
9 use Illuminate\Database\Query\Builder;
10 use Illuminate\Database\Query\JoinClause;
11 use Illuminate\Support\Collection;
12 use Illuminate\Support\Str;
20 protected $entityProvider;
28 * @var PermissionService
30 protected $permissionService;
34 * Acceptable operators to be used in a query
37 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 } else if (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(),
90 * Search a book for entities
92 public function searchBook(int $bookId, string $searchString): Collection
94 $opts = SearchOptions::fromString($searchString);
95 $entityTypes = ['page', 'chapter'];
96 $entityTypesToSearch = isset($opts->filters['type']) ? explode('|', $opts->filters['type']) : $entityTypes;
99 foreach ($entityTypesToSearch as $entityType) {
100 if (!in_array($entityType, $entityTypes)) {
103 $search = $this->buildEntitySearchQuery($opts, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
104 $results = $results->merge($search);
107 return $results->sortByDesc('score')->take(20);
111 * Search a chapter for entities
113 public function searchChapter(int $chapterId, string $searchString): Collection
115 $opts = SearchOptions::fromString($searchString);
116 $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.
124 * @return \Illuminate\Database\Eloquent\Collection|int|static[]
126 protected function searchEntityTable(SearchOptions $searchOpts, string $entityType = 'page', int $page = 1, int $count = 20, string $action = 'view', bool $getCount = false)
128 $query = $this->buildEntitySearchQuery($searchOpts, $entityType, $action);
130 return $query->count();
133 $query = $query->skip(($page-1) * $count)->take($count);
134 return $query->get();
138 * Create a search query for an entity
140 protected function buildEntitySearchQuery(SearchOptions $searchOpts, string $entityType = 'page', string $action = 'view'): EloquentBuilder
142 $entity = $this->entityProvider->get($entityType);
143 $entitySelect = $entity->newQuery();
145 // Handle normal search terms
146 if (count($searchOpts->searches) > 0) {
147 $rawScoreSum = $this->db->raw('SUM(score) as score');
148 $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', $rawScoreSum);
149 $subQuery->where('entity_type', '=', $entity->getMorphClass());
150 $subQuery->where(function (Builder $query) use ($searchOpts) {
151 foreach ($searchOpts->searches as $inputTerm) {
152 $query->orWhere('term', 'like', $inputTerm .'%');
154 })->groupBy('entity_type', 'entity_id');
155 $entitySelect->join($this->db->raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) {
156 $join->on('id', '=', 'entity_id');
157 })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
158 $entitySelect->mergeBindings($subQuery);
161 // Handle exact term matching
162 foreach ($searchOpts->exacts as $inputTerm) {
163 $entitySelect->where(function (EloquentBuilder $query) use ($inputTerm, $entity) {
164 $query->where('name', 'like', '%'.$inputTerm .'%')
165 ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
169 // Handle tag searches
170 foreach ($searchOpts->tags as $inputTerm) {
171 $this->applyTagSearch($entitySelect, $inputTerm);
175 foreach ($searchOpts->filters as $filterTerm => $filterValue) {
176 $functionName = Str::camel('filter_' . $filterTerm);
177 if (method_exists($this, $functionName)) {
178 $this->$functionName($entitySelect, $entity, $filterValue);
182 return $this->permissionService->enforceEntityRestrictions($entity, $entitySelect, $action);
186 * Get the available query operators as a regex escaped list.
188 protected function getRegexEscapedOperators(): string
190 $escapedOperators = [];
191 foreach ($this->queryOperators as $operator) {
192 $escapedOperators[] = preg_quote($operator);
194 return join('|', $escapedOperators);
198 * Apply a tag search term onto a entity query.
200 protected function applyTagSearch(EloquentBuilder $query, string $tagTerm): EloquentBuilder
202 preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
203 $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
204 $tagName = $tagSplit[1];
205 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
206 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
207 $validOperator = in_array($tagOperator, $this->queryOperators);
208 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
209 if (!empty($tagName)) {
210 $query->where('name', '=', $tagName);
212 if (is_numeric($tagValue) && $tagOperator !== 'like') {
213 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
214 // search the value as a string which prevents being able to do number-based operations
215 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
216 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
217 $query->whereRaw("value ${tagOperator} ${tagValue}");
219 $query->where('value', $tagOperator, $tagValue);
222 $query->where('name', '=', $tagName);
229 * Custom entity search filters
232 protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input)
235 $date = date_create($input);
236 } catch (\Exception $e) {
239 $query->where('updated_at', '>=', $date);
242 protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input)
245 $date = date_create($input);
246 } catch (\Exception $e) {
249 $query->where('updated_at', '<', $date);
252 protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input)
255 $date = date_create($input);
256 } catch (\Exception $e) {
259 $query->where('created_at', '>=', $date);
262 protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
265 $date = date_create($input);
266 } catch (\Exception $e) {
269 $query->where('created_at', '<', $date);
272 protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
274 $userSlug = $input === 'me' ? user()->slug : trim($input);
275 $user = User::query()->where('slug', '=', $userSlug)->first(['id']);
277 $query->where('created_by', '=', $user->id);
281 protected function filterUpdatedBy(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('updated_by', '=', $user->id);
290 protected function filterOwnedBy(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('owned_by', '=', $user->id);
299 protected function filterInName(EloquentBuilder $query, Entity $model, $input)
301 $query->where('name', 'like', '%' .$input. '%');
304 protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
306 $this->filterInName($query, $model, $input);
309 protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
311 $query->where($model->textField, 'like', '%' .$input. '%');
314 protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
316 $query->where('restricted', '=', true);
319 protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
321 $query->whereHas('views', function ($query) {
322 $query->where('user_id', '=', user()->id);
326 protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
328 $query->whereDoesntHave('views', function ($query) {
329 $query->where('user_id', '=', user()->id);
333 protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
335 $functionName = Str::camel('sort_by_' . $input);
336 if (method_exists($this, $functionName)) {
337 $this->$functionName($query, $model);
343 * Sorting filter options
346 protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
348 $commentsTable = $this->db->getTablePrefix() . 'comments';
349 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
350 $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');
352 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');