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(function(Builder $query) use ($terms) {
158 foreach ($terms['search'] as $inputTerm) {
159 $query->orWhere('term', 'like', $inputTerm .'%');
161 })->groupBy('entity_type', 'entity_id');
162 $entitySelect->join(\DB::raw('(' . $subQuery->toSql() . ') as s'), function(JoinClause $join) {
163 $join->on('id', '=', 'entity_id');
164 })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
165 $entitySelect->mergeBindings($subQuery);
168 // Handle exact term matching
169 if (count($terms['exact']) > 0) {
170 $entitySelect->where(function(\Illuminate\Database\Eloquent\Builder $query) use ($terms, $entity) {
171 foreach ($terms['exact'] as $inputTerm) {
172 $query->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($inputTerm, $entity) {
173 $query->where('name', 'like', '%'.$inputTerm .'%')
174 ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
180 // Handle tag searches
181 foreach ($terms['tags'] as $inputTerm) {
182 $this->applyTagSearch($entitySelect, $inputTerm);
186 foreach ($terms['filters'] as $filterTerm => $filterValue) {
187 $functionName = camel_case('filter_' . $filterTerm);
188 if (method_exists($this, $functionName)) $this->$functionName($entitySelect, $entity, $filterValue);
191 return $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, 'view');
196 * Parse a search string into components.
197 * @param $searchString
200 protected function parseSearchString($searchString)
210 'exact' => '/"(.*?)"/',
211 'tags' => '/\[(.*?)\]/',
212 'filters' => '/\{(.*?)\}/'
215 // Parse special terms
216 foreach ($patterns as $termType => $pattern) {
218 preg_match_all($pattern, $searchString, $matches);
219 if (count($matches) > 0) {
220 $terms[$termType] = $matches[1];
221 $searchString = preg_replace($pattern, '', $searchString);
225 // Parse standard terms
226 foreach (explode(' ', trim($searchString)) as $searchTerm) {
227 if ($searchTerm !== '') $terms['search'][] = $searchTerm;
230 // Split filter values out
232 foreach ($terms['filters'] as $filter) {
233 $explodedFilter = explode(':', $filter, 2);
234 $splitFilters[$explodedFilter[0]] = (count($explodedFilter) > 1) ? $explodedFilter[1] : '';
236 $terms['filters'] = $splitFilters;
242 * Get the available query operators as a regex escaped list.
245 protected function getRegexEscapedOperators()
247 $escapedOperators = [];
248 foreach ($this->queryOperators as $operator) {
249 $escapedOperators[] = preg_quote($operator);
251 return join('|', $escapedOperators);
255 * Apply a tag search term onto a entity query.
256 * @param \Illuminate\Database\Eloquent\Builder $query
257 * @param string $tagTerm
260 protected function applyTagSearch(\Illuminate\Database\Eloquent\Builder $query, $tagTerm) {
261 preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
262 $query->whereHas('tags', function(\Illuminate\Database\Eloquent\Builder $query) use ($tagSplit) {
263 $tagName = $tagSplit[1];
264 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
265 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
266 $validOperator = in_array($tagOperator, $this->queryOperators);
267 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
268 if (!empty($tagName)) $query->where('name', '=', $tagName);
269 if (is_numeric($tagValue) && $tagOperator !== 'like') {
270 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
271 // search the value as a string which prevents being able to do number-based operations
272 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
273 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
274 $query->whereRaw("value ${tagOperator} ${tagValue}");
276 $query->where('value', $tagOperator, $tagValue);
279 $query->where('name', '=', $tagName);
286 * Get an entity instance via type.
290 protected function getEntity($type)
292 return $this->entities[strtolower($type)];
296 * Index the given entity.
297 * @param Entity $entity
299 public function indexEntity(Entity $entity)
301 $this->deleteEntityTerms($entity);
302 $nameTerms = $this->generateTermArrayFromText($entity->name, 5);
303 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1);
304 $terms = array_merge($nameTerms, $bodyTerms);
305 foreach ($terms as $index => $term) {
306 $terms[$index]['entity_type'] = $entity->getMorphClass();
307 $terms[$index]['entity_id'] = $entity->id;
309 $this->searchTerm->newQuery()->insert($terms);
313 * Index multiple Entities at once
314 * @param Entity[] $entities
316 protected function indexEntities($entities) {
318 foreach ($entities as $entity) {
319 $nameTerms = $this->generateTermArrayFromText($entity->name, 5);
320 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1);
321 foreach (array_merge($nameTerms, $bodyTerms) as $term) {
322 $term['entity_id'] = $entity->id;
323 $term['entity_type'] = $entity->getMorphClass();
328 $chunkedTerms = array_chunk($terms, 500);
329 foreach ($chunkedTerms as $termChunk) {
330 $this->searchTerm->newQuery()->insert($termChunk);
335 * Delete and re-index the terms for all entities in the system.
337 public function indexAllEntities()
339 $this->searchTerm->truncate();
341 // Chunk through all books
342 $this->book->chunk(1000, function ($books) {
343 $this->indexEntities($books);
346 // Chunk through all chapters
347 $this->chapter->chunk(1000, function ($chapters) {
348 $this->indexEntities($chapters);
351 // Chunk through all pages
352 $this->page->chunk(1000, function ($pages) {
353 $this->indexEntities($pages);
358 * Delete related Entity search terms.
359 * @param Entity $entity
361 public function deleteEntityTerms(Entity $entity)
363 $entity->searchTerms()->delete();
367 * Create a scored term array from the given text.
369 * @param float|int $scoreAdjustment
372 protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
374 $tokenMap = []; // {TextToken => OccurrenceCount}
375 $splitText = explode(' ', $text);
376 foreach ($splitText as $token) {
377 if ($token === '') continue;
378 if (!isset($tokenMap[$token])) $tokenMap[$token] = 0;
383 foreach ($tokenMap as $token => $count) {
386 'score' => $count * $scoreAdjustment
396 * Custom entity search filters
399 protected function filterUpdatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
401 try { $date = date_create($input);
402 } catch (\Exception $e) {return;}
403 $query->where('updated_at', '>=', $date);
406 protected function filterUpdatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
408 try { $date = date_create($input);
409 } catch (\Exception $e) {return;}
410 $query->where('updated_at', '<', $date);
413 protected function filterCreatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
415 try { $date = date_create($input);
416 } catch (\Exception $e) {return;}
417 $query->where('created_at', '>=', $date);
420 protected function filterCreatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
422 try { $date = date_create($input);
423 } catch (\Exception $e) {return;}
424 $query->where('created_at', '<', $date);
427 protected function filterCreatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
429 if (!is_numeric($input) && $input !== 'me') return;
430 if ($input === 'me') $input = user()->id;
431 $query->where('created_by', '=', $input);
434 protected function filterUpdatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
436 if (!is_numeric($input) && $input !== 'me') return;
437 if ($input === 'me') $input = user()->id;
438 $query->where('updated_by', '=', $input);
441 protected function filterInName(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
443 $query->where('name', 'like', '%' .$input. '%');
446 protected function filterInTitle(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input) {$this->filterInName($query, $model, $input);}
448 protected function filterInBody(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
450 $query->where($model->textField, 'like', '%' .$input. '%');
453 protected function filterIsRestricted(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
455 $query->where('restricted', '=', true);
458 protected function filterViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
460 $query->whereHas('views', function($query) {
461 $query->where('user_id', '=', user()->id);
465 protected function filterNotViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
467 $query->whereDoesntHave('views', function($query) {
468 $query->where('user_id', '=', user()->id);