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
68 * @return array[int, Collection];
70 public function searchEntities($searchString, $entityType = 'all', $page = 1, $count = 20)
72 $terms = $this->parseSearchString($searchString);
73 $entityTypes = array_keys($this->entities);
74 $entityTypesToSearch = $entityTypes;
77 if ($entityType !== 'all') {
78 $entityTypesToSearch = $entityType;
79 } else if (isset($terms['filters']['type'])) {
80 $entityTypesToSearch = explode('|', $terms['filters']['type']);
85 foreach ($entityTypesToSearch as $entityType) {
86 if (!in_array($entityType, $entityTypes)) continue;
87 $search = $this->searchEntityTable($terms, $entityType, $page, $count);
88 $total += $this->searchEntityTable($terms, $entityType, $page, $count, true);
89 $results = $results->merge($search);
94 'count' => count($results),
95 'results' => $results->sortByDesc('score')
101 * Search a book for entities
102 * @param integer $bookId
103 * @param string $searchString
106 public function searchBook($bookId, $searchString)
108 $terms = $this->parseSearchString($searchString);
109 $entityTypes = ['page', 'chapter'];
110 $entityTypesToSearch = isset($terms['filters']['type']) ? explode('|', $terms['filters']['type']) : $entityTypes;
112 $results = collect();
113 foreach ($entityTypesToSearch as $entityType) {
114 if (!in_array($entityType, $entityTypes)) continue;
115 $search = $this->buildEntitySearchQuery($terms, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
116 $results = $results->merge($search);
118 return $results->sortByDesc('score')->take(20);
122 * Search a book for entities
123 * @param integer $chapterId
124 * @param string $searchString
127 public function searchChapter($chapterId, $searchString)
129 $terms = $this->parseSearchString($searchString);
130 $pages = $this->buildEntitySearchQuery($terms, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
131 return $pages->sortByDesc('score');
135 * Search across a particular entity type.
136 * @param array $terms
137 * @param string $entityType
140 * @param bool $getCount Return the total count of the search
141 * @return \Illuminate\Database\Eloquent\Collection|int|static[]
143 public function searchEntityTable($terms, $entityType = 'page', $page = 1, $count = 20, $getCount = false)
145 $query = $this->buildEntitySearchQuery($terms, $entityType);
146 if ($getCount) return $query->count();
148 $query = $query->skip(($page-1) * $count)->take($count);
149 return $query->get();
153 * Create a search query for an entity
154 * @param array $terms
155 * @param string $entityType
156 * @return \Illuminate\Database\Eloquent\Builder
158 protected function buildEntitySearchQuery($terms, $entityType = 'page')
160 $entity = $this->getEntity($entityType);
161 $entitySelect = $entity->newQuery();
163 // Handle normal search terms
164 if (count($terms['search']) > 0) {
165 $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', \DB::raw('SUM(score) as score'));
166 $subQuery->where('entity_type', '=', 'BookStack\\' . ucfirst($entityType));
167 $subQuery->where(function(Builder $query) use ($terms) {
168 foreach ($terms['search'] as $inputTerm) {
169 $query->orWhere('term', 'like', $inputTerm .'%');
171 })->groupBy('entity_type', 'entity_id');
172 $entitySelect->join(\DB::raw('(' . $subQuery->toSql() . ') as s'), function(JoinClause $join) {
173 $join->on('id', '=', 'entity_id');
174 })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
175 $entitySelect->mergeBindings($subQuery);
178 // Handle exact term matching
179 if (count($terms['exact']) > 0) {
180 $entitySelect->where(function(\Illuminate\Database\Eloquent\Builder $query) use ($terms, $entity) {
181 foreach ($terms['exact'] as $inputTerm) {
182 $query->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($inputTerm, $entity) {
183 $query->where('name', 'like', '%'.$inputTerm .'%')
184 ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
190 // Handle tag searches
191 foreach ($terms['tags'] as $inputTerm) {
192 $this->applyTagSearch($entitySelect, $inputTerm);
196 foreach ($terms['filters'] as $filterTerm => $filterValue) {
197 $functionName = camel_case('filter_' . $filterTerm);
198 if (method_exists($this, $functionName)) $this->$functionName($entitySelect, $entity, $filterValue);
201 return $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, 'view');
206 * Parse a search string into components.
207 * @param $searchString
210 protected function parseSearchString($searchString)
220 'exact' => '/"(.*?)"/',
221 'tags' => '/\[(.*?)\]/',
222 'filters' => '/\{(.*?)\}/'
225 // Parse special terms
226 foreach ($patterns as $termType => $pattern) {
228 preg_match_all($pattern, $searchString, $matches);
229 if (count($matches) > 0) {
230 $terms[$termType] = $matches[1];
231 $searchString = preg_replace($pattern, '', $searchString);
235 // Parse standard terms
236 foreach (explode(' ', trim($searchString)) as $searchTerm) {
237 if ($searchTerm !== '') $terms['search'][] = $searchTerm;
240 // Split filter values out
242 foreach ($terms['filters'] as $filter) {
243 $explodedFilter = explode(':', $filter, 2);
244 $splitFilters[$explodedFilter[0]] = (count($explodedFilter) > 1) ? $explodedFilter[1] : '';
246 $terms['filters'] = $splitFilters;
252 * Get the available query operators as a regex escaped list.
255 protected function getRegexEscapedOperators()
257 $escapedOperators = [];
258 foreach ($this->queryOperators as $operator) {
259 $escapedOperators[] = preg_quote($operator);
261 return join('|', $escapedOperators);
265 * Apply a tag search term onto a entity query.
266 * @param \Illuminate\Database\Eloquent\Builder $query
267 * @param string $tagTerm
270 protected function applyTagSearch(\Illuminate\Database\Eloquent\Builder $query, $tagTerm) {
271 preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
272 $query->whereHas('tags', function(\Illuminate\Database\Eloquent\Builder $query) use ($tagSplit) {
273 $tagName = $tagSplit[1];
274 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
275 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
276 $validOperator = in_array($tagOperator, $this->queryOperators);
277 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
278 if (!empty($tagName)) $query->where('name', '=', $tagName);
279 if (is_numeric($tagValue) && $tagOperator !== 'like') {
280 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
281 // search the value as a string which prevents being able to do number-based operations
282 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
283 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
284 $query->whereRaw("value ${tagOperator} ${tagValue}");
286 $query->where('value', $tagOperator, $tagValue);
289 $query->where('name', '=', $tagName);
296 * Get an entity instance via type.
300 protected function getEntity($type)
302 return $this->entities[strtolower($type)];
306 * Index the given entity.
307 * @param Entity $entity
309 public function indexEntity(Entity $entity)
311 $this->deleteEntityTerms($entity);
312 $nameTerms = $this->generateTermArrayFromText($entity->name, 5);
313 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1);
314 $terms = array_merge($nameTerms, $bodyTerms);
315 foreach ($terms as $index => $term) {
316 $terms[$index]['entity_type'] = $entity->getMorphClass();
317 $terms[$index]['entity_id'] = $entity->id;
319 $this->searchTerm->newQuery()->insert($terms);
323 * Index multiple Entities at once
324 * @param Entity[] $entities
326 protected function indexEntities($entities) {
328 foreach ($entities as $entity) {
329 $nameTerms = $this->generateTermArrayFromText($entity->name, 5);
330 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1);
331 foreach (array_merge($nameTerms, $bodyTerms) as $term) {
332 $term['entity_id'] = $entity->id;
333 $term['entity_type'] = $entity->getMorphClass();
338 $chunkedTerms = array_chunk($terms, 500);
339 foreach ($chunkedTerms as $termChunk) {
340 $this->searchTerm->newQuery()->insert($termChunk);
345 * Delete and re-index the terms for all entities in the system.
347 public function indexAllEntities()
349 $this->searchTerm->truncate();
351 // Chunk through all books
352 $this->book->chunk(1000, function ($books) {
353 $this->indexEntities($books);
356 // Chunk through all chapters
357 $this->chapter->chunk(1000, function ($chapters) {
358 $this->indexEntities($chapters);
361 // Chunk through all pages
362 $this->page->chunk(1000, function ($pages) {
363 $this->indexEntities($pages);
368 * Delete related Entity search terms.
369 * @param Entity $entity
371 public function deleteEntityTerms(Entity $entity)
373 $entity->searchTerms()->delete();
377 * Create a scored term array from the given text.
379 * @param float|int $scoreAdjustment
382 protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
384 $tokenMap = []; // {TextToken => OccurrenceCount}
385 $splitText = explode(' ', $text);
386 foreach ($splitText as $token) {
387 if ($token === '') continue;
388 if (!isset($tokenMap[$token])) $tokenMap[$token] = 0;
393 foreach ($tokenMap as $token => $count) {
396 'score' => $count * $scoreAdjustment
406 * Custom entity search filters
409 protected function filterUpdatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
411 try { $date = date_create($input);
412 } catch (\Exception $e) {return;}
413 $query->where('updated_at', '>=', $date);
416 protected function filterUpdatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
418 try { $date = date_create($input);
419 } catch (\Exception $e) {return;}
420 $query->where('updated_at', '<', $date);
423 protected function filterCreatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
425 try { $date = date_create($input);
426 } catch (\Exception $e) {return;}
427 $query->where('created_at', '>=', $date);
430 protected function filterCreatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
432 try { $date = date_create($input);
433 } catch (\Exception $e) {return;}
434 $query->where('created_at', '<', $date);
437 protected function filterCreatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
439 if (!is_numeric($input) && $input !== 'me') return;
440 if ($input === 'me') $input = user()->id;
441 $query->where('created_by', '=', $input);
444 protected function filterUpdatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
446 if (!is_numeric($input) && $input !== 'me') return;
447 if ($input === 'me') $input = user()->id;
448 $query->where('updated_by', '=', $input);
451 protected function filterInName(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
453 $query->where('name', 'like', '%' .$input. '%');
456 protected function filterInTitle(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input) {$this->filterInName($query, $model, $input);}
458 protected function filterInBody(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
460 $query->where($model->textField, 'like', '%' .$input. '%');
463 protected function filterIsRestricted(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
465 $query->where('restricted', '=', true);
468 protected function filterViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
470 $query->whereHas('views', function($query) {
471 $query->where('user_id', '=', user()->id);
475 protected function filterNotViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
477 $query->whereDoesntHave('views', function($query) {
478 $query->where('user_id', '=', user()->id);