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;
14 protected $searchTerm;
19 protected $permissionService;
23 * Acceptable operators to be used in a query
26 protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
29 * SearchService constructor.
30 * @param SearchTerm $searchTerm
32 * @param Chapter $chapter
34 * @param Connection $db
35 * @param PermissionService $permissionService
37 public function __construct(SearchTerm $searchTerm, Book $book, Chapter $chapter, Page $page, Connection $db, PermissionService $permissionService)
39 $this->searchTerm = $searchTerm;
41 $this->chapter = $chapter;
45 'page' => $this->page,
46 'chapter' => $this->chapter,
49 $this->permissionService = $permissionService;
53 * Search all entities in the system.
54 * @param string $searchString
55 * @param string $entityType
58 * @return array[int, Collection];
60 public function searchEntities($searchString, $entityType = 'all', $page = 1, $count = 20)
62 $terms = $this->parseSearchString($searchString);
63 $entityTypes = array_keys($this->entities);
64 $entityTypesToSearch = $entityTypes;
67 if ($entityType !== 'all') {
68 $entityTypesToSearch = $entityType;
69 } else if (isset($terms['filters']['type'])) {
70 $entityTypesToSearch = explode('|', $terms['filters']['type']);
75 foreach ($entityTypesToSearch as $entityType) {
76 if (!in_array($entityType, $entityTypes)) continue;
77 $search = $this->searchEntityTable($terms, $entityType, $page, $count);
78 $total += $this->searchEntityTable($terms, $entityType, $page, $count, true);
79 $results = $results->merge($search);
84 'count' => count($results),
85 'results' => $results->sortByDesc('score')
90 * Search across a particular entity type.
92 * @param string $entityType
95 * @param bool $getCount Return the total count of the search
96 * @return \Illuminate\Database\Eloquent\Collection|int|static[]
98 public function searchEntityTable($terms, $entityType = 'page', $page = 1, $count = 20, $getCount = false)
100 $entity = $this->getEntity($entityType);
101 $entitySelect = $entity->newQuery();
103 // Handle normal search terms
104 if (count($terms['search']) > 0) {
105 $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', \DB::raw('SUM(score) as score'));
106 $subQuery->where(function(Builder $query) use ($terms) {
107 foreach ($terms['search'] as $inputTerm) {
108 $query->orWhere('term', 'like', $inputTerm .'%');
110 })->groupBy('entity_type', 'entity_id');
111 $entitySelect->join(\DB::raw('(' . $subQuery->toSql() . ') as s'), function(JoinClause $join) {
112 $join->on('id', '=', 'entity_id');
113 })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
114 $entitySelect->mergeBindings($subQuery);
117 // Handle exact term matching
118 if (count($terms['exact']) > 0) {
119 $entitySelect->where(function(\Illuminate\Database\Eloquent\Builder $query) use ($terms, $entity) {
120 foreach ($terms['exact'] as $inputTerm) {
121 $query->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($inputTerm, $entity) {
122 $query->where('name', 'like', '%'.$inputTerm .'%')
123 ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
129 // Handle tag searches
130 foreach ($terms['tags'] as $inputTerm) {
131 $this->applyTagSearch($entitySelect, $inputTerm);
135 foreach ($terms['filters'] as $filterTerm => $filterValue) {
136 $functionName = camel_case('filter_' . $filterTerm);
137 if (method_exists($this, $functionName)) $this->$functionName($entitySelect, $entity, $filterValue);
140 $query = $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, 'view');
141 if ($getCount) return $query->count();
143 $query = $query->skip(($page-1) * $count)->take($count);
144 return $query->get();
149 * Parse a search string into components.
150 * @param $searchString
153 protected function parseSearchString($searchString)
163 'exact' => '/"(.*?)"/',
164 'tags' => '/\[(.*?)\]/',
165 'filters' => '/\{(.*?)\}/'
168 // Parse special terms
169 foreach ($patterns as $termType => $pattern) {
171 preg_match_all($pattern, $searchString, $matches);
172 if (count($matches) > 0) {
173 $terms[$termType] = $matches[1];
174 $searchString = preg_replace($pattern, '', $searchString);
178 // Parse standard terms
179 foreach (explode(' ', trim($searchString)) as $searchTerm) {
180 if ($searchTerm !== '') $terms['search'][] = $searchTerm;
183 // Split filter values out
185 foreach ($terms['filters'] as $filter) {
186 $explodedFilter = explode(':', $filter, 2);
187 $splitFilters[$explodedFilter[0]] = (count($explodedFilter) > 1) ? $explodedFilter[1] : '';
189 $terms['filters'] = $splitFilters;
195 * Get the available query operators as a regex escaped list.
198 protected function getRegexEscapedOperators()
200 $escapedOperators = [];
201 foreach ($this->queryOperators as $operator) {
202 $escapedOperators[] = preg_quote($operator);
204 return join('|', $escapedOperators);
208 * Apply a tag search term onto a entity query.
209 * @param \Illuminate\Database\Eloquent\Builder $query
210 * @param string $tagTerm
213 protected function applyTagSearch(\Illuminate\Database\Eloquent\Builder $query, $tagTerm) {
214 preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
215 $query->whereHas('tags', function(\Illuminate\Database\Eloquent\Builder $query) use ($tagSplit) {
216 $tagName = $tagSplit[1];
217 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
218 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
219 $validOperator = in_array($tagOperator, $this->queryOperators);
220 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
221 if (!empty($tagName)) $query->where('name', '=', $tagName);
222 if (is_numeric($tagValue) && $tagOperator !== 'like') {
223 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
224 // search the value as a string which prevents being able to do number-based operations
225 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
226 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
227 $query->whereRaw("value ${tagOperator} ${tagValue}");
229 $query->where('value', $tagOperator, $tagValue);
232 $query->where('name', '=', $tagName);
239 * Get an entity instance via type.
243 protected function getEntity($type)
245 return $this->entities[strtolower($type)];
249 * Index the given entity.
250 * @param Entity $entity
252 public function indexEntity(Entity $entity)
254 $this->deleteEntityTerms($entity);
255 $nameTerms = $this->generateTermArrayFromText($entity->name, 5);
256 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1);
257 $terms = array_merge($nameTerms, $bodyTerms);
258 foreach ($terms as $index => $term) {
259 $terms[$index]['entity_type'] = $entity->getMorphClass();
260 $terms[$index]['entity_id'] = $entity->id;
262 $this->searchTerm->newQuery()->insert($terms);
266 * Index multiple Entities at once
267 * @param Entity[] $entities
269 protected function indexEntities($entities) {
271 foreach ($entities as $entity) {
272 $nameTerms = $this->generateTermArrayFromText($entity->name, 5);
273 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1);
274 foreach (array_merge($nameTerms, $bodyTerms) as $term) {
275 $term['entity_id'] = $entity->id;
276 $term['entity_type'] = $entity->getMorphClass();
281 $chunkedTerms = array_chunk($terms, 500);
282 foreach ($chunkedTerms as $termChunk) {
283 $this->searchTerm->newQuery()->insert($termChunk);
288 * Delete and re-index the terms for all entities in the system.
290 public function indexAllEntities()
292 $this->searchTerm->truncate();
294 // Chunk through all books
295 $this->book->chunk(1000, function ($books) {
296 $this->indexEntities($books);
299 // Chunk through all chapters
300 $this->chapter->chunk(1000, function ($chapters) {
301 $this->indexEntities($chapters);
304 // Chunk through all pages
305 $this->page->chunk(1000, function ($pages) {
306 $this->indexEntities($pages);
311 * Delete related Entity search terms.
312 * @param Entity $entity
314 public function deleteEntityTerms(Entity $entity)
316 $entity->searchTerms()->delete();
320 * Create a scored term array from the given text.
322 * @param float|int $scoreAdjustment
325 protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
327 $tokenMap = []; // {TextToken => OccurrenceCount}
328 $splitText = explode(' ', $text);
329 foreach ($splitText as $token) {
330 if ($token === '') continue;
331 if (!isset($tokenMap[$token])) $tokenMap[$token] = 0;
336 foreach ($tokenMap as $token => $count) {
339 'score' => $count * $scoreAdjustment
349 * Custom entity search filters
352 protected function filterUpdatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
354 try { $date = date_create($input);
355 } catch (\Exception $e) {return;}
356 $query->where('updated_at', '>=', $date);
359 protected function filterUpdatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
361 try { $date = date_create($input);
362 } catch (\Exception $e) {return;}
363 $query->where('updated_at', '<', $date);
366 protected function filterCreatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
368 try { $date = date_create($input);
369 } catch (\Exception $e) {return;}
370 $query->where('created_at', '>=', $date);
373 protected function filterCreatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
375 try { $date = date_create($input);
376 } catch (\Exception $e) {return;}
377 $query->where('created_at', '<', $date);
380 protected function filterCreatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
382 if (!is_numeric($input) && $input !== 'me') return;
383 if ($input === 'me') $input = user()->id;
384 $query->where('created_by', '=', $input);
387 protected function filterUpdatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
389 if (!is_numeric($input) && $input !== 'me') return;
390 if ($input === 'me') $input = user()->id;
391 $query->where('updated_by', '=', $input);
394 protected function filterInName(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
396 $query->where('name', 'like', '%' .$input. '%');
399 protected function filterInTitle(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input) {$this->filterInName($query, $model, $input);}
401 protected function filterInBody(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
403 $query->where($model->textField, 'like', '%' .$input. '%');
406 protected function filterIsRestricted(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
408 $query->where('restricted', '=', true);
411 protected function filterViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
413 $query->whereHas('views', function($query) {
414 $query->where('user_id', '=', user()->id);
418 protected function filterNotViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
420 $query->whereDoesntHave('views', function($query) {
421 $query->where('user_id', '=', user()->id);