1 <?php namespace BookStack\Services;
4 use BookStack\Bookshelf;
8 use BookStack\SearchTerm;
9 use Illuminate\Database\Connection;
10 use Illuminate\Database\Query\Builder;
11 use Illuminate\Database\Query\JoinClause;
12 use Illuminate\Support\Collection;
16 protected $searchTerm;
22 protected $permissionService;
30 * Acceptable operators to be used in a query
33 protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
36 * SearchService constructor.
37 * @param SearchTerm $searchTerm
38 * @param Bookshelf $bookshelf
40 * @param Chapter $chapter
42 * @param Connection $db
43 * @param PermissionService $permissionService
45 public function __construct(SearchTerm $searchTerm, Bookshelf $bookshelf, Book $book, Chapter $chapter, Page $page, Connection $db, PermissionService $permissionService)
47 $this->searchTerm = $searchTerm;
48 $this->bookshelf = $bookshelf;
50 $this->chapter = $chapter;
54 'bookshelf' => $this->bookshelf,
55 'page' => $this->page,
56 'chapter' => $this->chapter,
59 $this->permissionService = $permissionService;
63 * Set the database connection
64 * @param Connection $connection
66 public function setConnection(Connection $connection)
68 $this->db = $connection;
72 * Search all entities in the system.
73 * @param string $searchString
74 * @param string $entityType
76 * @param int $count - Count of each entity to search, Total returned could can be larger and not guaranteed.
77 * @param string $action
78 * @return array[int, Collection];
80 public function searchEntities($searchString, $entityType = 'all', $page = 1, $count = 20, $action = 'view')
82 $terms = $this->parseSearchString($searchString);
83 $entityTypes = array_keys($this->entities);
84 $entityTypesToSearch = $entityTypes;
86 if ($entityType !== 'all') {
87 $entityTypesToSearch = $entityType;
88 } else if (isset($terms['filters']['type'])) {
89 $entityTypesToSearch = explode('|', $terms['filters']['type']);
96 foreach ($entityTypesToSearch as $entityType) {
97 if (!in_array($entityType, $entityTypes)) {
100 $search = $this->searchEntityTable($terms, $entityType, $page, $count, $action);
101 $entityTotal = $this->searchEntityTable($terms, $entityType, $page, $count, $action, true);
102 if ($entityTotal > $page * $count) {
105 $total += $entityTotal;
106 $results = $results->merge($search);
111 'count' => count($results),
112 'has_more' => $hasMore,
113 'results' => $results->sortByDesc('score')->values()
119 * Search a book for entities
120 * @param integer $bookId
121 * @param string $searchString
124 public function searchBook($bookId, $searchString)
126 $terms = $this->parseSearchString($searchString);
127 $entityTypes = ['page', 'chapter'];
128 $entityTypesToSearch = isset($terms['filters']['type']) ? explode('|', $terms['filters']['type']) : $entityTypes;
130 $results = collect();
131 foreach ($entityTypesToSearch as $entityType) {
132 if (!in_array($entityType, $entityTypes)) {
135 $search = $this->buildEntitySearchQuery($terms, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
136 $results = $results->merge($search);
138 return $results->sortByDesc('score')->take(20);
142 * Search a book for entities
143 * @param integer $chapterId
144 * @param string $searchString
147 public function searchChapter($chapterId, $searchString)
149 $terms = $this->parseSearchString($searchString);
150 $pages = $this->buildEntitySearchQuery($terms, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
151 return $pages->sortByDesc('score');
155 * Search across a particular entity type.
156 * @param array $terms
157 * @param string $entityType
160 * @param string $action
161 * @param bool $getCount Return the total count of the search
162 * @return \Illuminate\Database\Eloquent\Collection|int|static[]
164 public function searchEntityTable($terms, $entityType = 'page', $page = 1, $count = 20, $action = 'view', $getCount = false)
166 $query = $this->buildEntitySearchQuery($terms, $entityType, $action);
168 return $query->count();
171 $query = $query->skip(($page-1) * $count)->take($count);
172 return $query->get();
176 * Create a search query for an entity
177 * @param array $terms
178 * @param string $entityType
179 * @param string $action
180 * @return \Illuminate\Database\Eloquent\Builder
182 protected function buildEntitySearchQuery($terms, $entityType = 'page', $action = 'view')
184 $entity = $this->getEntity($entityType);
185 $entitySelect = $entity->newQuery();
187 // Handle normal search terms
188 if (count($terms['search']) > 0) {
189 $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', \DB::raw('SUM(score) as score'));
190 $subQuery->where('entity_type', '=', 'BookStack\\' . ucfirst($entityType));
191 $subQuery->where(function (Builder $query) use ($terms) {
192 foreach ($terms['search'] as $inputTerm) {
193 $query->orWhere('term', 'like', $inputTerm .'%');
195 })->groupBy('entity_type', 'entity_id');
196 $entitySelect->join(\DB::raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) {
197 $join->on('id', '=', 'entity_id');
198 })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
199 $entitySelect->mergeBindings($subQuery);
202 // Handle exact term matching
203 if (count($terms['exact']) > 0) {
204 $entitySelect->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($terms, $entity) {
205 foreach ($terms['exact'] as $inputTerm) {
206 $query->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($inputTerm, $entity) {
207 $query->where('name', 'like', '%'.$inputTerm .'%')
208 ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
214 // Handle tag searches
215 foreach ($terms['tags'] as $inputTerm) {
216 $this->applyTagSearch($entitySelect, $inputTerm);
220 foreach ($terms['filters'] as $filterTerm => $filterValue) {
221 $functionName = camel_case('filter_' . $filterTerm);
222 if (method_exists($this, $functionName)) {
223 $this->$functionName($entitySelect, $entity, $filterValue);
227 return $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, $action);
232 * Parse a search string into components.
233 * @param $searchString
236 protected function parseSearchString($searchString)
246 'exact' => '/"(.*?)"/',
247 'tags' => '/\[(.*?)\]/',
248 'filters' => '/\{(.*?)\}/'
251 // Parse special terms
252 foreach ($patterns as $termType => $pattern) {
254 preg_match_all($pattern, $searchString, $matches);
255 if (count($matches) > 0) {
256 $terms[$termType] = $matches[1];
257 $searchString = preg_replace($pattern, '', $searchString);
261 // Parse standard terms
262 foreach (explode(' ', trim($searchString)) as $searchTerm) {
263 if ($searchTerm !== '') {
264 $terms['search'][] = $searchTerm;
268 // Split filter values out
270 foreach ($terms['filters'] as $filter) {
271 $explodedFilter = explode(':', $filter, 2);
272 $splitFilters[$explodedFilter[0]] = (count($explodedFilter) > 1) ? $explodedFilter[1] : '';
274 $terms['filters'] = $splitFilters;
280 * Get the available query operators as a regex escaped list.
283 protected function getRegexEscapedOperators()
285 $escapedOperators = [];
286 foreach ($this->queryOperators as $operator) {
287 $escapedOperators[] = preg_quote($operator);
289 return join('|', $escapedOperators);
293 * Apply a tag search term onto a entity query.
294 * @param \Illuminate\Database\Eloquent\Builder $query
295 * @param string $tagTerm
298 protected function applyTagSearch(\Illuminate\Database\Eloquent\Builder $query, $tagTerm)
300 preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
301 $query->whereHas('tags', function (\Illuminate\Database\Eloquent\Builder $query) use ($tagSplit) {
302 $tagName = $tagSplit[1];
303 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
304 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
305 $validOperator = in_array($tagOperator, $this->queryOperators);
306 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
307 if (!empty($tagName)) {
308 $query->where('name', '=', $tagName);
310 if (is_numeric($tagValue) && $tagOperator !== 'like') {
311 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
312 // search the value as a string which prevents being able to do number-based operations
313 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
314 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
315 $query->whereRaw("value ${tagOperator} ${tagValue}");
317 $query->where('value', $tagOperator, $tagValue);
320 $query->where('name', '=', $tagName);
327 * Get an entity instance via type.
331 protected function getEntity($type)
333 return $this->entities[strtolower($type)];
337 * Index the given entity.
338 * @param Entity $entity
340 public function indexEntity(Entity $entity)
342 $this->deleteEntityTerms($entity);
343 $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
344 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
345 $terms = array_merge($nameTerms, $bodyTerms);
346 foreach ($terms as $index => $term) {
347 $terms[$index]['entity_type'] = $entity->getMorphClass();
348 $terms[$index]['entity_id'] = $entity->id;
350 $this->searchTerm->newQuery()->insert($terms);
354 * Index multiple Entities at once
355 * @param Entity[] $entities
357 protected function indexEntities($entities)
360 foreach ($entities as $entity) {
361 $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
362 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
363 foreach (array_merge($nameTerms, $bodyTerms) as $term) {
364 $term['entity_id'] = $entity->id;
365 $term['entity_type'] = $entity->getMorphClass();
370 $chunkedTerms = array_chunk($terms, 500);
371 foreach ($chunkedTerms as $termChunk) {
372 $this->searchTerm->newQuery()->insert($termChunk);
377 * Delete and re-index the terms for all entities in the system.
379 public function indexAllEntities()
381 $this->searchTerm->truncate();
383 foreach ($this->entities as $entityModel) {
384 $selectFields = ['id', 'name', $entityModel->textField];
385 $entityModel->newQuery()->select($selectFields)->chunk(1000, function ($entities) {
386 $this->indexEntities($entities);
392 * Delete related Entity search terms.
393 * @param Entity $entity
395 public function deleteEntityTerms(Entity $entity)
397 $entity->searchTerms()->delete();
401 * Create a scored term array from the given text.
403 * @param float|int $scoreAdjustment
406 protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
408 $tokenMap = []; // {TextToken => OccurrenceCount}
409 $splitChars = " \n\t.,!?:;()[]{}<>`'\"";
410 $token = strtok($text, $splitChars);
412 while ($token !== false) {
413 if (!isset($tokenMap[$token])) {
414 $tokenMap[$token] = 0;
417 $token = strtok($splitChars);
421 foreach ($tokenMap as $token => $count) {
424 'score' => $count * $scoreAdjustment
434 * Custom entity search filters
437 protected function filterUpdatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
440 $date = date_create($input);
441 } catch (\Exception $e) {
444 $query->where('updated_at', '>=', $date);
447 protected function filterUpdatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
450 $date = date_create($input);
451 } catch (\Exception $e) {
454 $query->where('updated_at', '<', $date);
457 protected function filterCreatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
460 $date = date_create($input);
461 } catch (\Exception $e) {
464 $query->where('created_at', '>=', $date);
467 protected function filterCreatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
470 $date = date_create($input);
471 } catch (\Exception $e) {
474 $query->where('created_at', '<', $date);
477 protected function filterCreatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
479 if (!is_numeric($input) && $input !== 'me') {
482 if ($input === 'me') {
485 $query->where('created_by', '=', $input);
488 protected function filterUpdatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
490 if (!is_numeric($input) && $input !== 'me') {
493 if ($input === 'me') {
496 $query->where('updated_by', '=', $input);
499 protected function filterInName(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
501 $query->where('name', 'like', '%' .$input. '%');
504 protected function filterInTitle(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
506 $this->filterInName($query, $model, $input);
509 protected function filterInBody(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
511 $query->where($model->textField, 'like', '%' .$input. '%');
514 protected function filterIsRestricted(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
516 $query->where('restricted', '=', true);
519 protected function filterViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
521 $query->whereHas('views', function ($query) {
522 $query->where('user_id', '=', user()->id);
526 protected function filterNotViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
528 $query->whereDoesntHave('views', function ($query) {
529 $query->where('user_id', '=', user()->id);
533 protected function filterSortBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
535 $functionName = camel_case('sort_by_' . $input);
536 if (method_exists($this, $functionName)) {
537 $this->$functionName($query, $model);
543 * Sorting filter options
546 protected function sortByLastCommented(\Illuminate\Database\Eloquent\Builder $query, Entity $model)
548 $commentsTable = $this->db->getTablePrefix() . 'comments';
549 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
550 $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');
552 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');