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 * Search all entities in the system.
55 * @param string $searchString
56 * @param string $entityType
59 * @return array[int, Collection];
61 public function searchEntities($searchString, $entityType = 'all', $page = 1, $count = 20)
63 $terms = $this->parseSearchString($searchString);
64 $entityTypes = array_keys($this->entities);
65 $entityTypesToSearch = $entityTypes;
68 if ($entityType !== 'all') {
69 $entityTypesToSearch = $entityType;
70 } else if (isset($terms['filters']['type'])) {
71 $entityTypesToSearch = explode('|', $terms['filters']['type']);
76 foreach ($entityTypesToSearch as $entityType) {
77 if (!in_array($entityType, $entityTypes)) continue;
78 $search = $this->searchEntityTable($terms, $entityType, $page, $count);
79 $total += $this->searchEntityTable($terms, $entityType, $page, $count, true);
80 $results = $results->merge($search);
85 'count' => count($results),
86 'results' => $results->sortByDesc('score')
92 * Search a book for entities
93 * @param integer $bookId
94 * @param string $searchString
97 public function searchBook($bookId, $searchString)
99 $terms = $this->parseSearchString($searchString);
100 $entityTypes = ['page', 'chapter'];
101 $entityTypesToSearch = isset($terms['filters']['type']) ? explode('|', $terms['filters']['type']) : $entityTypes;
103 $results = collect();
104 foreach ($entityTypesToSearch as $entityType) {
105 if (!in_array($entityType, $entityTypes)) continue;
106 $search = $this->buildEntitySearchQuery($terms, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
107 $results = $results->merge($search);
109 return $results->sortByDesc('score')->take(20);
113 * Search a book for entities
114 * @param integer $chapterId
115 * @param string $searchString
118 public function searchChapter($chapterId, $searchString)
120 $terms = $this->parseSearchString($searchString);
121 $pages = $this->buildEntitySearchQuery($terms, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
122 return $pages->sortByDesc('score');
126 * Search across a particular entity type.
127 * @param array $terms
128 * @param string $entityType
131 * @param bool $getCount Return the total count of the search
132 * @return \Illuminate\Database\Eloquent\Collection|int|static[]
134 public function searchEntityTable($terms, $entityType = 'page', $page = 1, $count = 20, $getCount = false)
136 $query = $this->buildEntitySearchQuery($terms, $entityType);
137 if ($getCount) return $query->count();
139 $query = $query->skip(($page-1) * $count)->take($count);
140 return $query->get();
144 * Create a search query for an entity
145 * @param array $terms
146 * @param string $entityType
147 * @return \Illuminate\Database\Eloquent\Builder
149 protected function buildEntitySearchQuery($terms, $entityType = 'page')
151 $entity = $this->getEntity($entityType);
152 $entitySelect = $entity->newQuery();
154 // Handle normal search terms
155 if (count($terms['search']) > 0) {
156 $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', \DB::raw('SUM(score) as score'));
157 $subQuery->where('entity_type', '=', 'BookStack\\' . ucfirst($entityType));
158 $subQuery->where(function(Builder $query) use ($terms) {
159 foreach ($terms['search'] as $inputTerm) {
160 $query->orWhere('term', 'like', $inputTerm .'%');
162 })->groupBy('entity_type', 'entity_id');
163 $entitySelect->join(\DB::raw('(' . $subQuery->toSql() . ') as s'), function(JoinClause $join) {
164 $join->on('id', '=', 'entity_id');
165 })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
166 $entitySelect->mergeBindings($subQuery);
169 // Handle exact term matching
170 if (count($terms['exact']) > 0) {
171 $entitySelect->where(function(\Illuminate\Database\Eloquent\Builder $query) use ($terms, $entity) {
172 foreach ($terms['exact'] as $inputTerm) {
173 $query->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($inputTerm, $entity) {
174 $query->where('name', 'like', '%'.$inputTerm .'%')
175 ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
181 // Handle tag searches
182 foreach ($terms['tags'] as $inputTerm) {
183 $this->applyTagSearch($entitySelect, $inputTerm);
187 foreach ($terms['filters'] as $filterTerm => $filterValue) {
188 $functionName = camel_case('filter_' . $filterTerm);
189 if (method_exists($this, $functionName)) $this->$functionName($entitySelect, $entity, $filterValue);
192 return $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, 'view');
197 * Parse a search string into components.
198 * @param $searchString
201 protected function parseSearchString($searchString)
211 'exact' => '/"(.*?)"/',
212 'tags' => '/\[(.*?)\]/',
213 'filters' => '/\{(.*?)\}/'
216 // Parse special terms
217 foreach ($patterns as $termType => $pattern) {
219 preg_match_all($pattern, $searchString, $matches);
220 if (count($matches) > 0) {
221 $terms[$termType] = $matches[1];
222 $searchString = preg_replace($pattern, '', $searchString);
226 // Parse standard terms
227 foreach (explode(' ', trim($searchString)) as $searchTerm) {
228 if ($searchTerm !== '') $terms['search'][] = $searchTerm;
231 // Split filter values out
233 foreach ($terms['filters'] as $filter) {
234 $explodedFilter = explode(':', $filter, 2);
235 $splitFilters[$explodedFilter[0]] = (count($explodedFilter) > 1) ? $explodedFilter[1] : '';
237 $terms['filters'] = $splitFilters;
243 * Get the available query operators as a regex escaped list.
246 protected function getRegexEscapedOperators()
248 $escapedOperators = [];
249 foreach ($this->queryOperators as $operator) {
250 $escapedOperators[] = preg_quote($operator);
252 return join('|', $escapedOperators);
256 * Apply a tag search term onto a entity query.
257 * @param \Illuminate\Database\Eloquent\Builder $query
258 * @param string $tagTerm
261 protected function applyTagSearch(\Illuminate\Database\Eloquent\Builder $query, $tagTerm) {
262 preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
263 $query->whereHas('tags', function(\Illuminate\Database\Eloquent\Builder $query) use ($tagSplit) {
264 $tagName = $tagSplit[1];
265 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
266 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
267 $validOperator = in_array($tagOperator, $this->queryOperators);
268 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
269 if (!empty($tagName)) $query->where('name', '=', $tagName);
270 if (is_numeric($tagValue) && $tagOperator !== 'like') {
271 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
272 // search the value as a string which prevents being able to do number-based operations
273 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
274 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
275 $query->whereRaw("value ${tagOperator} ${tagValue}");
277 $query->where('value', $tagOperator, $tagValue);
280 $query->where('name', '=', $tagName);
287 * Get an entity instance via type.
291 protected function getEntity($type)
293 return $this->entities[strtolower($type)];
297 * Index the given entity.
298 * @param Entity $entity
300 public function indexEntity(Entity $entity)
302 $this->deleteEntityTerms($entity);
303 $nameTerms = $this->generateTermArrayFromText($entity->name, 5);
304 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1);
305 $terms = array_merge($nameTerms, $bodyTerms);
306 foreach ($terms as $index => $term) {
307 $terms[$index]['entity_type'] = $entity->getMorphClass();
308 $terms[$index]['entity_id'] = $entity->id;
310 $this->searchTerm->newQuery()->insert($terms);
314 * Index multiple Entities at once
315 * @param Entity[] $entities
317 protected function indexEntities($entities) {
319 foreach ($entities as $entity) {
320 $nameTerms = $this->generateTermArrayFromText($entity->name, 5);
321 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1);
322 foreach (array_merge($nameTerms, $bodyTerms) as $term) {
323 $term['entity_id'] = $entity->id;
324 $term['entity_type'] = $entity->getMorphClass();
329 $chunkedTerms = array_chunk($terms, 500);
330 foreach ($chunkedTerms as $termChunk) {
331 $this->searchTerm->newQuery()->insert($termChunk);
336 * Delete and re-index the terms for all entities in the system.
338 public function indexAllEntities()
340 $this->searchTerm->truncate();
342 // Chunk through all books
343 $this->book->chunk(1000, function ($books) {
344 $this->indexEntities($books);
347 // Chunk through all chapters
348 $this->chapter->chunk(1000, function ($chapters) {
349 $this->indexEntities($chapters);
352 // Chunk through all pages
353 $this->page->chunk(1000, function ($pages) {
354 $this->indexEntities($pages);
359 * Delete related Entity search terms.
360 * @param Entity $entity
362 public function deleteEntityTerms(Entity $entity)
364 $entity->searchTerms()->delete();
368 * Create a scored term array from the given text.
370 * @param float|int $scoreAdjustment
373 protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
375 $tokenMap = []; // {TextToken => OccurrenceCount}
376 $splitText = explode(' ', $text);
377 foreach ($splitText as $token) {
378 if ($token === '') continue;
379 if (!isset($tokenMap[$token])) $tokenMap[$token] = 0;
384 foreach ($tokenMap as $token => $count) {
387 'score' => $count * $scoreAdjustment
397 * Custom entity search filters
400 protected function filterUpdatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
402 try { $date = date_create($input);
403 } catch (\Exception $e) {return;}
404 $query->where('updated_at', '>=', $date);
407 protected function filterUpdatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
409 try { $date = date_create($input);
410 } catch (\Exception $e) {return;}
411 $query->where('updated_at', '<', $date);
414 protected function filterCreatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
416 try { $date = date_create($input);
417 } catch (\Exception $e) {return;}
418 $query->where('created_at', '>=', $date);
421 protected function filterCreatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
423 try { $date = date_create($input);
424 } catch (\Exception $e) {return;}
425 $query->where('created_at', '<', $date);
428 protected function filterCreatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
430 if (!is_numeric($input) && $input !== 'me') return;
431 if ($input === 'me') $input = user()->id;
432 $query->where('created_by', '=', $input);
435 protected function filterUpdatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
437 if (!is_numeric($input) && $input !== 'me') return;
438 if ($input === 'me') $input = user()->id;
439 $query->where('updated_by', '=', $input);
442 protected function filterInName(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
444 $query->where('name', 'like', '%' .$input. '%');
447 protected function filterInTitle(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input) {$this->filterInName($query, $model, $input);}
449 protected function filterInBody(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
451 $query->where($model->textField, 'like', '%' .$input. '%');
454 protected function filterIsRestricted(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
456 $query->where('restricted', '=', true);
459 protected function filterViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
461 $query->whereHas('views', function($query) {
462 $query->where('user_id', '=', user()->id);
466 protected function filterNotViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
468 $query->whereDoesntHave('views', function($query) {
469 $query->where('user_id', '=', user()->id);