1 <?php namespace BookStack\Services;
7 use BookStack\SearchTerm;
8 use Illuminate\Database\Connection;
9 use Illuminate\Database\Query\Builder;
10 use Illuminate\Database\Query\JoinClause;
11 use Illuminate\Support\Collection;
15 protected $searchTerm;
20 protected $permissionService;
24 * Acceptable operators to be used in a query
27 protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
30 * SearchService constructor.
31 * @param SearchTerm $searchTerm
33 * @param Chapter $chapter
35 * @param Connection $db
36 * @param PermissionService $permissionService
38 public function __construct(SearchTerm $searchTerm, Book $book, Chapter $chapter, Page $page, Connection $db, PermissionService $permissionService)
40 $this->searchTerm = $searchTerm;
42 $this->chapter = $chapter;
46 'page' => $this->page,
47 'chapter' => $this->chapter,
50 $this->permissionService = $permissionService;
54 * Set the database connection
55 * @param Connection $connection
57 public function setConnection(Connection $connection)
59 $this->db = $connection;
63 * Search all entities in the system.
64 * @param string $searchString
65 * @param string $entityType
67 * @param int $count - Count of each entity to search, Total returned could can be larger and not guaranteed.
68 * @return array[int, Collection];
70 public function searchEntities($searchString, $entityType = 'all', $page = 1, $count = 20, $action = 'view')
72 $terms = $this->parseSearchString($searchString);
73 $entityTypes = array_keys($this->entities);
74 $entityTypesToSearch = $entityTypes;
76 if ($entityType !== 'all') {
77 $entityTypesToSearch = $entityType;
78 } else if (isset($terms['filters']['type'])) {
79 $entityTypesToSearch = explode('|', $terms['filters']['type']);
86 foreach ($entityTypesToSearch as $entityType) {
87 if (!in_array($entityType, $entityTypes)) {
90 $search = $this->searchEntityTable($terms, $entityType, $page, $count, $action);
91 $entityTotal = $this->searchEntityTable($terms, $entityType, $page, $count, $action, true);
92 if ($entityTotal > $page * $count) {
95 $total += $entityTotal;
96 $results = $results->merge($search);
101 'count' => count($results),
102 'has_more' => $hasMore,
103 'results' => $results->sortByDesc('score')->values()
109 * Search a book for entities
110 * @param integer $bookId
111 * @param string $searchString
114 public function searchBook($bookId, $searchString)
116 $terms = $this->parseSearchString($searchString);
117 $entityTypes = ['page', 'chapter'];
118 $entityTypesToSearch = isset($terms['filters']['type']) ? explode('|', $terms['filters']['type']) : $entityTypes;
120 $results = collect();
121 foreach ($entityTypesToSearch as $entityType) {
122 if (!in_array($entityType, $entityTypes)) {
125 $search = $this->buildEntitySearchQuery($terms, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
126 $results = $results->merge($search);
128 return $results->sortByDesc('score')->take(20);
132 * Search a book for entities
133 * @param integer $chapterId
134 * @param string $searchString
137 public function searchChapter($chapterId, $searchString)
139 $terms = $this->parseSearchString($searchString);
140 $pages = $this->buildEntitySearchQuery($terms, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
141 return $pages->sortByDesc('score');
145 * Search across a particular entity type.
146 * @param array $terms
147 * @param string $entityType
150 * @param string $action
151 * @param bool $getCount Return the total count of the search
152 * @return \Illuminate\Database\Eloquent\Collection|int|static[]
154 public function searchEntityTable($terms, $entityType = 'page', $page = 1, $count = 20, $action = 'view', $getCount = false)
156 $query = $this->buildEntitySearchQuery($terms, $entityType, $action);
158 return $query->count();
161 $query = $query->skip(($page-1) * $count)->take($count);
162 return $query->get();
166 * Create a search query for an entity
167 * @param array $terms
168 * @param string $entityType
169 * @param string $action
170 * @return \Illuminate\Database\Eloquent\Builder
172 protected function buildEntitySearchQuery($terms, $entityType = 'page', $action = 'view')
174 $entity = $this->getEntity($entityType);
175 $entitySelect = $entity->newQuery();
177 // Handle normal search terms
178 if (count($terms['search']) > 0) {
179 $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', \DB::raw('SUM(score) as score'));
180 $subQuery->where('entity_type', '=', 'BookStack\\' . ucfirst($entityType));
181 $subQuery->where(function (Builder $query) use ($terms) {
182 foreach ($terms['search'] as $inputTerm) {
183 $query->orWhere('term', 'like', $inputTerm .'%');
185 })->groupBy('entity_type', 'entity_id');
186 $entitySelect->join(\DB::raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) {
187 $join->on('id', '=', 'entity_id');
188 })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
189 $entitySelect->mergeBindings($subQuery);
192 // Handle exact term matching
193 if (count($terms['exact']) > 0) {
194 $entitySelect->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($terms, $entity) {
195 foreach ($terms['exact'] as $inputTerm) {
196 $query->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($inputTerm, $entity) {
197 $query->where('name', 'like', '%'.$inputTerm .'%')
198 ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
204 // Handle tag searches
205 foreach ($terms['tags'] as $inputTerm) {
206 $this->applyTagSearch($entitySelect, $inputTerm);
210 foreach ($terms['filters'] as $filterTerm => $filterValue) {
211 $functionName = camel_case('filter_' . $filterTerm);
212 if (method_exists($this, $functionName)) {
213 $this->$functionName($entitySelect, $entity, $filterValue);
217 return $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, $action);
222 * Parse a search string into components.
223 * @param $searchString
226 protected function parseSearchString($searchString)
236 'exact' => '/"(.*?)"/',
237 'tags' => '/\[(.*?)\]/',
238 'filters' => '/\{(.*?)\}/'
241 // Parse special terms
242 foreach ($patterns as $termType => $pattern) {
244 preg_match_all($pattern, $searchString, $matches);
245 if (count($matches) > 0) {
246 $terms[$termType] = $matches[1];
247 $searchString = preg_replace($pattern, '', $searchString);
251 // Parse standard terms
252 foreach (explode(' ', trim($searchString)) as $searchTerm) {
253 if ($searchTerm !== '') {
254 $terms['search'][] = $searchTerm;
258 // Split filter values out
260 foreach ($terms['filters'] as $filter) {
261 $explodedFilter = explode(':', $filter, 2);
262 $splitFilters[$explodedFilter[0]] = (count($explodedFilter) > 1) ? $explodedFilter[1] : '';
264 $terms['filters'] = $splitFilters;
270 * Get the available query operators as a regex escaped list.
273 protected function getRegexEscapedOperators()
275 $escapedOperators = [];
276 foreach ($this->queryOperators as $operator) {
277 $escapedOperators[] = preg_quote($operator);
279 return join('|', $escapedOperators);
283 * Apply a tag search term onto a entity query.
284 * @param \Illuminate\Database\Eloquent\Builder $query
285 * @param string $tagTerm
288 protected function applyTagSearch(\Illuminate\Database\Eloquent\Builder $query, $tagTerm)
290 preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
291 $query->whereHas('tags', function (\Illuminate\Database\Eloquent\Builder $query) use ($tagSplit) {
292 $tagName = $tagSplit[1];
293 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
294 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
295 $validOperator = in_array($tagOperator, $this->queryOperators);
296 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
297 if (!empty($tagName)) {
298 $query->where('name', '=', $tagName);
300 if (is_numeric($tagValue) && $tagOperator !== 'like') {
301 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
302 // search the value as a string which prevents being able to do number-based operations
303 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
304 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
305 $query->whereRaw("value ${tagOperator} ${tagValue}");
307 $query->where('value', $tagOperator, $tagValue);
310 $query->where('name', '=', $tagName);
317 * Get an entity instance via type.
321 protected function getEntity($type)
323 return $this->entities[strtolower($type)];
327 * Index the given entity.
328 * @param Entity $entity
330 public function indexEntity(Entity $entity)
332 $this->deleteEntityTerms($entity);
333 $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
334 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
335 $terms = array_merge($nameTerms, $bodyTerms);
336 foreach ($terms as $index => $term) {
337 $terms[$index]['entity_type'] = $entity->getMorphClass();
338 $terms[$index]['entity_id'] = $entity->id;
340 $this->searchTerm->newQuery()->insert($terms);
344 * Index multiple Entities at once
345 * @param Entity[] $entities
347 protected function indexEntities($entities)
350 foreach ($entities as $entity) {
351 $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
352 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
353 foreach (array_merge($nameTerms, $bodyTerms) as $term) {
354 $term['entity_id'] = $entity->id;
355 $term['entity_type'] = $entity->getMorphClass();
360 $chunkedTerms = array_chunk($terms, 500);
361 foreach ($chunkedTerms as $termChunk) {
362 $this->searchTerm->newQuery()->insert($termChunk);
367 * Delete and re-index the terms for all entities in the system.
369 public function indexAllEntities()
371 $this->searchTerm->truncate();
373 // Chunk through all books
374 $this->book->chunk(1000, function ($books) {
375 $this->indexEntities($books);
378 // Chunk through all chapters
379 $this->chapter->chunk(1000, function ($chapters) {
380 $this->indexEntities($chapters);
383 // Chunk through all pages
384 $this->page->chunk(1000, function ($pages) {
385 $this->indexEntities($pages);
390 * Delete related Entity search terms.
391 * @param Entity $entity
393 public function deleteEntityTerms(Entity $entity)
395 $entity->searchTerms()->delete();
399 * Create a scored term array from the given text.
401 * @param float|int $scoreAdjustment
404 protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
406 $tokenMap = []; // {TextToken => OccurrenceCount}
407 $splitChars = " \n\t.,!?:;()[]{}<>`'\"";
408 $token = strtok($text, $splitChars);
410 while ($token !== false) {
411 if (!isset($tokenMap[$token])) {
412 $tokenMap[$token] = 0;
415 $token = strtok($splitChars);
419 foreach ($tokenMap as $token => $count) {
422 'score' => $count * $scoreAdjustment
432 * Custom entity search filters
435 protected function filterUpdatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
438 $date = date_create($input);
439 } catch (\Exception $e) {
442 $query->where('updated_at', '>=', $date);
445 protected function filterUpdatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
448 $date = date_create($input);
449 } catch (\Exception $e) {
452 $query->where('updated_at', '<', $date);
455 protected function filterCreatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
458 $date = date_create($input);
459 } catch (\Exception $e) {
462 $query->where('created_at', '>=', $date);
465 protected function filterCreatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
468 $date = date_create($input);
469 } catch (\Exception $e) {
472 $query->where('created_at', '<', $date);
475 protected function filterCreatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
477 if (!is_numeric($input) && $input !== 'me') {
480 if ($input === 'me') {
483 $query->where('created_by', '=', $input);
486 protected function filterUpdatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
488 if (!is_numeric($input) && $input !== 'me') {
491 if ($input === 'me') {
494 $query->where('updated_by', '=', $input);
497 protected function filterInName(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
499 $query->where('name', 'like', '%' .$input. '%');
502 protected function filterInTitle(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
504 $this->filterInName($query, $model, $input);
507 protected function filterInBody(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
509 $query->where($model->textField, 'like', '%' .$input. '%');
512 protected function filterIsRestricted(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
514 $query->where('restricted', '=', true);
517 protected function filterViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
519 $query->whereHas('views', function ($query) {
520 $query->where('user_id', '=', user()->id);
524 protected function filterNotViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
526 $query->whereDoesntHave('views', function ($query) {
527 $query->where('user_id', '=', user()->id);
531 protected function filterSortBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
533 $functionName = camel_case('sort_by_' . $input);
534 if (method_exists($this, $functionName)) {
535 $this->$functionName($query, $model);
541 * Sorting filter options
544 protected function sortByLastCommented(\Illuminate\Database\Eloquent\Builder $query, Entity $model)
546 $commentsTable = $this->db->getTablePrefix() . 'comments';
547 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
548 $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');
550 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');