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;
76 if ($entityType !== 'all') {
77 $entityTypesToSearch = $entityType;
78 } else if (isset($terms['filters']['type'])) {
79 $entityTypesToSearch = explode('|', $terms['filters']['type']);
85 foreach ($entityTypesToSearch as $entityType) {
86 if (!in_array($entityType, $entityTypes)) {
89 $search = $this->searchEntityTable($terms, $entityType, $page, $count + 1);
90 $total += $this->searchEntityTable($terms, $entityType, $page, $count + 1, true);
91 $results = $results->merge($search);
96 'count' => count($results),
97 'has_more' => $results->count() > $count,
98 'results' => $results->sortByDesc('score')->slice(0, $count)->values()
104 * Search a book for entities
105 * @param integer $bookId
106 * @param string $searchString
109 public function searchBook($bookId, $searchString)
111 $terms = $this->parseSearchString($searchString);
112 $entityTypes = ['page', 'chapter'];
113 $entityTypesToSearch = isset($terms['filters']['type']) ? explode('|', $terms['filters']['type']) : $entityTypes;
115 $results = collect();
116 foreach ($entityTypesToSearch as $entityType) {
117 if (!in_array($entityType, $entityTypes)) {
120 $search = $this->buildEntitySearchQuery($terms, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
121 $results = $results->merge($search);
123 return $results->sortByDesc('score')->take(20);
127 * Search a book for entities
128 * @param integer $chapterId
129 * @param string $searchString
132 public function searchChapter($chapterId, $searchString)
134 $terms = $this->parseSearchString($searchString);
135 $pages = $this->buildEntitySearchQuery($terms, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
136 return $pages->sortByDesc('score');
140 * Search across a particular entity type.
141 * @param array $terms
142 * @param string $entityType
145 * @param bool $getCount Return the total count of the search
146 * @return \Illuminate\Database\Eloquent\Collection|int|static[]
148 public function searchEntityTable($terms, $entityType = 'page', $page = 1, $count = 20, $getCount = false)
150 $query = $this->buildEntitySearchQuery($terms, $entityType);
152 return $query->count();
155 $query = $query->skip(($page-1) * $count)->take($count);
156 return $query->get();
160 * Create a search query for an entity
161 * @param array $terms
162 * @param string $entityType
163 * @return \Illuminate\Database\Eloquent\Builder
165 protected function buildEntitySearchQuery($terms, $entityType = 'page')
167 $entity = $this->getEntity($entityType);
168 $entitySelect = $entity->newQuery();
170 // Handle normal search terms
171 if (count($terms['search']) > 0) {
172 $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', \DB::raw('SUM(score) as score'));
173 $subQuery->where('entity_type', '=', 'BookStack\\' . ucfirst($entityType));
174 $subQuery->where(function (Builder $query) use ($terms) {
175 foreach ($terms['search'] as $inputTerm) {
176 $query->orWhere('term', 'like', $inputTerm .'%');
178 })->groupBy('entity_type', 'entity_id');
179 $entitySelect->join(\DB::raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) {
180 $join->on('id', '=', 'entity_id');
181 })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
182 $entitySelect->mergeBindings($subQuery);
185 // Handle exact term matching
186 if (count($terms['exact']) > 0) {
187 $entitySelect->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($terms, $entity) {
188 foreach ($terms['exact'] as $inputTerm) {
189 $query->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($inputTerm, $entity) {
190 $query->where('name', 'like', '%'.$inputTerm .'%')
191 ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
197 // Handle tag searches
198 foreach ($terms['tags'] as $inputTerm) {
199 $this->applyTagSearch($entitySelect, $inputTerm);
203 foreach ($terms['filters'] as $filterTerm => $filterValue) {
204 $functionName = camel_case('filter_' . $filterTerm);
205 if (method_exists($this, $functionName)) {
206 $this->$functionName($entitySelect, $entity, $filterValue);
210 return $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, 'view');
215 * Parse a search string into components.
216 * @param $searchString
219 protected function parseSearchString($searchString)
229 'exact' => '/"(.*?)"/',
230 'tags' => '/\[(.*?)\]/',
231 'filters' => '/\{(.*?)\}/'
234 // Parse special terms
235 foreach ($patterns as $termType => $pattern) {
237 preg_match_all($pattern, $searchString, $matches);
238 if (count($matches) > 0) {
239 $terms[$termType] = $matches[1];
240 $searchString = preg_replace($pattern, '', $searchString);
244 // Parse standard terms
245 foreach (explode(' ', trim($searchString)) as $searchTerm) {
246 if ($searchTerm !== '') {
247 $terms['search'][] = $searchTerm;
251 // Split filter values out
253 foreach ($terms['filters'] as $filter) {
254 $explodedFilter = explode(':', $filter, 2);
255 $splitFilters[$explodedFilter[0]] = (count($explodedFilter) > 1) ? $explodedFilter[1] : '';
257 $terms['filters'] = $splitFilters;
263 * Get the available query operators as a regex escaped list.
266 protected function getRegexEscapedOperators()
268 $escapedOperators = [];
269 foreach ($this->queryOperators as $operator) {
270 $escapedOperators[] = preg_quote($operator);
272 return join('|', $escapedOperators);
276 * Apply a tag search term onto a entity query.
277 * @param \Illuminate\Database\Eloquent\Builder $query
278 * @param string $tagTerm
281 protected function applyTagSearch(\Illuminate\Database\Eloquent\Builder $query, $tagTerm)
283 preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
284 $query->whereHas('tags', function (\Illuminate\Database\Eloquent\Builder $query) use ($tagSplit) {
285 $tagName = $tagSplit[1];
286 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
287 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
288 $validOperator = in_array($tagOperator, $this->queryOperators);
289 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
290 if (!empty($tagName)) {
291 $query->where('name', '=', $tagName);
293 if (is_numeric($tagValue) && $tagOperator !== 'like') {
294 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
295 // search the value as a string which prevents being able to do number-based operations
296 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
297 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
298 $query->whereRaw("value ${tagOperator} ${tagValue}");
300 $query->where('value', $tagOperator, $tagValue);
303 $query->where('name', '=', $tagName);
310 * Get an entity instance via type.
314 protected function getEntity($type)
316 return $this->entities[strtolower($type)];
320 * Index the given entity.
321 * @param Entity $entity
323 public function indexEntity(Entity $entity)
325 $this->deleteEntityTerms($entity);
326 $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
327 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
328 $terms = array_merge($nameTerms, $bodyTerms);
329 foreach ($terms as $index => $term) {
330 $terms[$index]['entity_type'] = $entity->getMorphClass();
331 $terms[$index]['entity_id'] = $entity->id;
333 $this->searchTerm->newQuery()->insert($terms);
337 * Index multiple Entities at once
338 * @param Entity[] $entities
340 protected function indexEntities($entities)
343 foreach ($entities as $entity) {
344 $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
345 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
346 foreach (array_merge($nameTerms, $bodyTerms) as $term) {
347 $term['entity_id'] = $entity->id;
348 $term['entity_type'] = $entity->getMorphClass();
353 $chunkedTerms = array_chunk($terms, 500);
354 foreach ($chunkedTerms as $termChunk) {
355 $this->searchTerm->newQuery()->insert($termChunk);
360 * Delete and re-index the terms for all entities in the system.
362 public function indexAllEntities()
364 $this->searchTerm->truncate();
366 // Chunk through all books
367 $this->book->chunk(1000, function ($books) {
368 $this->indexEntities($books);
371 // Chunk through all chapters
372 $this->chapter->chunk(1000, function ($chapters) {
373 $this->indexEntities($chapters);
376 // Chunk through all pages
377 $this->page->chunk(1000, function ($pages) {
378 $this->indexEntities($pages);
383 * Delete related Entity search terms.
384 * @param Entity $entity
386 public function deleteEntityTerms(Entity $entity)
388 $entity->searchTerms()->delete();
392 * Create a scored term array from the given text.
394 * @param float|int $scoreAdjustment
397 protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
399 $tokenMap = []; // {TextToken => OccurrenceCount}
400 $splitChars = " \n\t.,!?:;()[]{}<>`'\"";
401 $token = strtok($text, $splitChars);
403 while ($token !== false) {
404 if (!isset($tokenMap[$token])) {
405 $tokenMap[$token] = 0;
408 $token = strtok($splitChars);
412 foreach ($tokenMap as $token => $count) {
415 'score' => $count * $scoreAdjustment
425 * Custom entity search filters
428 protected function filterUpdatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
431 $date = date_create($input);
432 } catch (\Exception $e) {
435 $query->where('updated_at', '>=', $date);
438 protected function filterUpdatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
441 $date = date_create($input);
442 } catch (\Exception $e) {
445 $query->where('updated_at', '<', $date);
448 protected function filterCreatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
451 $date = date_create($input);
452 } catch (\Exception $e) {
455 $query->where('created_at', '>=', $date);
458 protected function filterCreatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
461 $date = date_create($input);
462 } catch (\Exception $e) {
465 $query->where('created_at', '<', $date);
468 protected function filterCreatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
470 if (!is_numeric($input) && $input !== 'me') {
473 if ($input === 'me') {
476 $query->where('created_by', '=', $input);
479 protected function filterUpdatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
481 if (!is_numeric($input) && $input !== 'me') {
484 if ($input === 'me') {
487 $query->where('updated_by', '=', $input);
490 protected function filterInName(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
492 $query->where('name', 'like', '%' .$input. '%');
495 protected function filterInTitle(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
497 $this->filterInName($query, $model, $input);
500 protected function filterInBody(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
502 $query->where($model->textField, 'like', '%' .$input. '%');
505 protected function filterIsRestricted(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
507 $query->where('restricted', '=', true);
510 protected function filterViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
512 $query->whereHas('views', function ($query) {
513 $query->where('user_id', '=', user()->id);
517 protected function filterNotViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
519 $query->whereDoesntHave('views', function ($query) {
520 $query->where('user_id', '=', user()->id);
524 protected function filterSortBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
526 $functionName = camel_case('sort_by_' . $input);
527 if (method_exists($this, $functionName)) {
528 $this->$functionName($query, $model);
534 * Sorting filter options
537 protected function sortByLastCommented(\Illuminate\Database\Eloquent\Builder $query, Entity $model)
539 $commentsTable = $this->db->getTablePrefix() . 'comments';
540 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
541 $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');
543 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');