1 <?php namespace BookStack\Entities;
3 use BookStack\Auth\Permissions\PermissionService;
4 use Illuminate\Database\Connection;
5 use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
6 use Illuminate\Database\Query\Builder;
7 use Illuminate\Database\Query\JoinClause;
8 use Illuminate\Support\Collection;
15 protected $searchTerm;
20 protected $entityProvider;
28 * @var PermissionService
30 protected $permissionService;
34 * Acceptable operators to be used in a query
37 protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
40 * SearchService constructor.
41 * @param SearchTerm $searchTerm
42 * @param EntityProvider $entityProvider
43 * @param Connection $db
44 * @param PermissionService $permissionService
46 public function __construct(SearchTerm $searchTerm, EntityProvider $entityProvider, Connection $db, PermissionService $permissionService)
48 $this->searchTerm = $searchTerm;
49 $this->entityProvider = $entityProvider;
51 $this->permissionService = $permissionService;
55 * Set the database connection
56 * @param Connection $connection
58 public function setConnection(Connection $connection)
60 $this->db = $connection;
64 * Search all entities in the system.
65 * @param string $searchString
66 * @param string $entityType
68 * @param int $count - Count of each entity to search, Total returned could can be larger and not guaranteed.
69 * @param string $action
70 * @return array[int, Collection];
72 public function searchEntities($searchString, $entityType = 'all', $page = 1, $count = 20, $action = 'view')
74 $terms = $this->parseSearchString($searchString);
75 $entityTypes = array_keys($this->entityProvider->all());
76 $entityTypesToSearch = $entityTypes;
78 if ($entityType !== 'all') {
79 $entityTypesToSearch = $entityType;
80 } else if (isset($terms['filters']['type'])) {
81 $entityTypesToSearch = explode('|', $terms['filters']['type']);
88 foreach ($entityTypesToSearch as $entityType) {
89 if (!in_array($entityType, $entityTypes)) {
92 $search = $this->searchEntityTable($terms, $entityType, $page, $count, $action);
93 $entityTotal = $this->searchEntityTable($terms, $entityType, $page, $count, $action, true);
94 if ($entityTotal > $page * $count) {
97 $total += $entityTotal;
98 $results = $results->merge($search);
103 'count' => count($results),
104 'has_more' => $hasMore,
105 'results' => $results->sortByDesc('score')->values()
111 * Search a book for entities
112 * @param integer $bookId
113 * @param string $searchString
116 public function searchBook($bookId, $searchString)
118 $terms = $this->parseSearchString($searchString);
119 $entityTypes = ['page', 'chapter'];
120 $entityTypesToSearch = isset($terms['filters']['type']) ? explode('|', $terms['filters']['type']) : $entityTypes;
122 $results = collect();
123 foreach ($entityTypesToSearch as $entityType) {
124 if (!in_array($entityType, $entityTypes)) {
127 $search = $this->buildEntitySearchQuery($terms, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
128 $results = $results->merge($search);
130 return $results->sortByDesc('score')->take(20);
134 * Search a book for entities
135 * @param integer $chapterId
136 * @param string $searchString
139 public function searchChapter($chapterId, $searchString)
141 $terms = $this->parseSearchString($searchString);
142 $pages = $this->buildEntitySearchQuery($terms, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
143 return $pages->sortByDesc('score');
147 * Search across a particular entity type.
148 * @param array $terms
149 * @param string $entityType
152 * @param string $action
153 * @param bool $getCount Return the total count of the search
154 * @return \Illuminate\Database\Eloquent\Collection|int|static[]
156 public function searchEntityTable($terms, $entityType = 'page', $page = 1, $count = 20, $action = 'view', $getCount = false)
158 $query = $this->buildEntitySearchQuery($terms, $entityType, $action);
160 return $query->count();
163 $query = $query->skip(($page-1) * $count)->take($count);
164 return $query->get();
168 * Create a search query for an entity
169 * @param array $terms
170 * @param string $entityType
171 * @param string $action
172 * @return EloquentBuilder
174 protected function buildEntitySearchQuery($terms, $entityType = 'page', $action = 'view')
176 $entity = $this->entityProvider->get($entityType);
177 $entitySelect = $entity->newQuery();
179 // Handle normal search terms
180 if (count($terms['search']) > 0) {
181 $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', \DB::raw('SUM(score) as score'));
182 $subQuery->where('entity_type', '=', $entity->getMorphClass());
183 $subQuery->where(function (Builder $query) use ($terms) {
184 foreach ($terms['search'] as $inputTerm) {
185 $query->orWhere('term', 'like', $inputTerm .'%');
187 })->groupBy('entity_type', 'entity_id');
188 $entitySelect->join(\DB::raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) {
189 $join->on('id', '=', 'entity_id');
190 })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
191 $entitySelect->mergeBindings($subQuery);
194 // Handle exact term matching
195 if (count($terms['exact']) > 0) {
196 $entitySelect->where(function (EloquentBuilder $query) use ($terms, $entity) {
197 foreach ($terms['exact'] as $inputTerm) {
198 $query->where(function (EloquentBuilder $query) use ($inputTerm, $entity) {
199 $query->where('name', 'like', '%'.$inputTerm .'%')
200 ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
206 // Handle tag searches
207 foreach ($terms['tags'] as $inputTerm) {
208 $this->applyTagSearch($entitySelect, $inputTerm);
212 foreach ($terms['filters'] as $filterTerm => $filterValue) {
213 $functionName = camel_case('filter_' . $filterTerm);
214 if (method_exists($this, $functionName)) {
215 $this->$functionName($entitySelect, $entity, $filterValue);
219 return $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, $action);
224 * Parse a search string into components.
225 * @param $searchString
228 protected function parseSearchString($searchString)
238 'exact' => '/"(.*?)"/',
239 'tags' => '/\[(.*?)\]/',
240 'filters' => '/\{(.*?)\}/'
243 // Parse special terms
244 foreach ($patterns as $termType => $pattern) {
246 preg_match_all($pattern, $searchString, $matches);
247 if (count($matches) > 0) {
248 $terms[$termType] = $matches[1];
249 $searchString = preg_replace($pattern, '', $searchString);
253 // Parse standard terms
254 foreach (explode(' ', trim($searchString)) as $searchTerm) {
255 if ($searchTerm !== '') {
256 $terms['search'][] = $searchTerm;
260 // Split filter values out
262 foreach ($terms['filters'] as $filter) {
263 $explodedFilter = explode(':', $filter, 2);
264 $splitFilters[$explodedFilter[0]] = (count($explodedFilter) > 1) ? $explodedFilter[1] : '';
266 $terms['filters'] = $splitFilters;
272 * Get the available query operators as a regex escaped list.
275 protected function getRegexEscapedOperators()
277 $escapedOperators = [];
278 foreach ($this->queryOperators as $operator) {
279 $escapedOperators[] = preg_quote($operator);
281 return join('|', $escapedOperators);
285 * Apply a tag search term onto a entity query.
286 * @param EloquentBuilder $query
287 * @param string $tagTerm
290 protected function applyTagSearch(EloquentBuilder $query, $tagTerm)
292 preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
293 $query->whereHas('tags', function (EloquentBuilder $query) use ($tagSplit) {
294 $tagName = $tagSplit[1];
295 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
296 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
297 $validOperator = in_array($tagOperator, $this->queryOperators);
298 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
299 if (!empty($tagName)) {
300 $query->where('name', '=', $tagName);
302 if (is_numeric($tagValue) && $tagOperator !== 'like') {
303 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
304 // search the value as a string which prevents being able to do number-based operations
305 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
306 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
307 $query->whereRaw("value ${tagOperator} ${tagValue}");
309 $query->where('value', $tagOperator, $tagValue);
312 $query->where('name', '=', $tagName);
319 * Index the given entity.
320 * @param Entity $entity
322 public function indexEntity(Entity $entity)
324 $this->deleteEntityTerms($entity);
325 $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
326 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
327 $terms = array_merge($nameTerms, $bodyTerms);
328 foreach ($terms as $index => $term) {
329 $terms[$index]['entity_type'] = $entity->getMorphClass();
330 $terms[$index]['entity_id'] = $entity->id;
332 $this->searchTerm->newQuery()->insert($terms);
336 * Index multiple Entities at once
337 * @param \BookStack\Entities\Entity[] $entities
339 protected function indexEntities($entities)
342 foreach ($entities as $entity) {
343 $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
344 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
345 foreach (array_merge($nameTerms, $bodyTerms) as $term) {
346 $term['entity_id'] = $entity->id;
347 $term['entity_type'] = $entity->getMorphClass();
352 $chunkedTerms = array_chunk($terms, 500);
353 foreach ($chunkedTerms as $termChunk) {
354 $this->searchTerm->newQuery()->insert($termChunk);
359 * Delete and re-index the terms for all entities in the system.
361 public function indexAllEntities()
363 $this->searchTerm->truncate();
365 foreach ($this->entityProvider->all() as $entityModel) {
366 $selectFields = ['id', 'name', $entityModel->textField];
367 $entityModel->newQuery()->select($selectFields)->chunk(1000, function ($entities) {
368 $this->indexEntities($entities);
374 * Delete related Entity search terms.
375 * @param Entity $entity
377 public function deleteEntityTerms(Entity $entity)
379 $entity->searchTerms()->delete();
383 * Create a scored term array from the given text.
385 * @param float|int $scoreAdjustment
388 protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
390 $tokenMap = []; // {TextToken => OccurrenceCount}
391 $splitChars = " \n\t.,!?:;()[]{}<>`'\"";
392 $token = strtok($text, $splitChars);
394 while ($token !== false) {
395 if (!isset($tokenMap[$token])) {
396 $tokenMap[$token] = 0;
399 $token = strtok($splitChars);
403 foreach ($tokenMap as $token => $count) {
406 'score' => $count * $scoreAdjustment
416 * Custom entity search filters
419 protected function filterUpdatedAfter(EloquentBuilder $query, Entity $model, $input)
422 $date = date_create($input);
423 } catch (\Exception $e) {
426 $query->where('updated_at', '>=', $date);
429 protected function filterUpdatedBefore(EloquentBuilder $query, Entity $model, $input)
432 $date = date_create($input);
433 } catch (\Exception $e) {
436 $query->where('updated_at', '<', $date);
439 protected function filterCreatedAfter(EloquentBuilder $query, Entity $model, $input)
442 $date = date_create($input);
443 } catch (\Exception $e) {
446 $query->where('created_at', '>=', $date);
449 protected function filterCreatedBefore(EloquentBuilder $query, Entity $model, $input)
452 $date = date_create($input);
453 } catch (\Exception $e) {
456 $query->where('created_at', '<', $date);
459 protected function filterCreatedBy(EloquentBuilder $query, Entity $model, $input)
461 if (!is_numeric($input) && $input !== 'me') {
464 if ($input === 'me') {
467 $query->where('created_by', '=', $input);
470 protected function filterUpdatedBy(EloquentBuilder $query, Entity $model, $input)
472 if (!is_numeric($input) && $input !== 'me') {
475 if ($input === 'me') {
478 $query->where('updated_by', '=', $input);
481 protected function filterInName(EloquentBuilder $query, Entity $model, $input)
483 $query->where('name', 'like', '%' .$input. '%');
486 protected function filterInTitle(EloquentBuilder $query, Entity $model, $input)
488 $this->filterInName($query, $model, $input);
491 protected function filterInBody(EloquentBuilder $query, Entity $model, $input)
493 $query->where($model->textField, 'like', '%' .$input. '%');
496 protected function filterIsRestricted(EloquentBuilder $query, Entity $model, $input)
498 $query->where('restricted', '=', true);
501 protected function filterViewedByMe(EloquentBuilder $query, Entity $model, $input)
503 $query->whereHas('views', function ($query) {
504 $query->where('user_id', '=', user()->id);
508 protected function filterNotViewedByMe(EloquentBuilder $query, Entity $model, $input)
510 $query->whereDoesntHave('views', function ($query) {
511 $query->where('user_id', '=', user()->id);
515 protected function filterSortBy(EloquentBuilder $query, Entity $model, $input)
517 $functionName = camel_case('sort_by_' . $input);
518 if (method_exists($this, $functionName)) {
519 $this->$functionName($query, $model);
525 * Sorting filter options
528 protected function sortByLastCommented(EloquentBuilder $query, Entity $model)
530 $commentsTable = $this->db->getTablePrefix() . 'comments';
531 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
532 $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');
534 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');