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
67 * @param int $count - Count of each entity to search, Total returned could can be larger and not guaranteed.
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']);
86 foreach ($entityTypesToSearch as $entityType) {
87 if (!in_array($entityType, $entityTypes)) {
90 $search = $this->searchEntityTable($terms, $entityType, $page, $count);
91 $entityTotal = $this->searchEntityTable($terms, $entityType, $page, $count, true);
92 if ($entityTotal > $page * $count) {
95 $total += $entityTotal;
96 $results = $results->merge($search);
101 'count' => count($results),
102 'has_more' => $hasMore,
103 'results' => $results->sortByDesc('score')->values()
109 * Search a book for entities
110 * @param integer $bookId
111 * @param string $searchString
114 public function searchBook($bookId, $searchString)
116 $terms = $this->parseSearchString($searchString);
117 $entityTypes = ['page', 'chapter'];
118 $entityTypesToSearch = isset($terms['filters']['type']) ? explode('|', $terms['filters']['type']) : $entityTypes;
120 $results = collect();
121 foreach ($entityTypesToSearch as $entityType) {
122 if (!in_array($entityType, $entityTypes)) {
125 $search = $this->buildEntitySearchQuery($terms, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
126 $results = $results->merge($search);
128 return $results->sortByDesc('score')->take(20);
132 * Search a book for entities
133 * @param integer $chapterId
134 * @param string $searchString
137 public function searchChapter($chapterId, $searchString)
139 $terms = $this->parseSearchString($searchString);
140 $pages = $this->buildEntitySearchQuery($terms, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
141 return $pages->sortByDesc('score');
145 * Search across a particular entity type.
146 * @param array $terms
147 * @param string $entityType
150 * @param bool $getCount Return the total count of the search
151 * @return \Illuminate\Database\Eloquent\Collection|int|static[]
153 public function searchEntityTable($terms, $entityType = 'page', $page = 1, $count = 20, $getCount = false)
155 $query = $this->buildEntitySearchQuery($terms, $entityType);
157 return $query->count();
160 $query = $query->skip(($page-1) * $count)->take($count);
161 return $query->get();
165 * Create a search query for an entity
166 * @param array $terms
167 * @param string $entityType
168 * @return \Illuminate\Database\Eloquent\Builder
170 protected function buildEntitySearchQuery($terms, $entityType = 'page')
172 $entity = $this->getEntity($entityType);
173 $entitySelect = $entity->newQuery();
175 // Handle normal search terms
176 if (count($terms['search']) > 0) {
177 $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', \DB::raw('SUM(score) as score'));
178 $subQuery->where('entity_type', '=', 'BookStack\\' . ucfirst($entityType));
179 $subQuery->where(function (Builder $query) use ($terms) {
180 foreach ($terms['search'] as $inputTerm) {
181 $query->orWhere('term', 'like', $inputTerm .'%');
183 })->groupBy('entity_type', 'entity_id');
184 $entitySelect->join(\DB::raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) {
185 $join->on('id', '=', 'entity_id');
186 })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
187 $entitySelect->mergeBindings($subQuery);
190 // Handle exact term matching
191 if (count($terms['exact']) > 0) {
192 $entitySelect->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($terms, $entity) {
193 foreach ($terms['exact'] as $inputTerm) {
194 $query->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($inputTerm, $entity) {
195 $query->where('name', 'like', '%'.$inputTerm .'%')
196 ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
202 // Handle tag searches
203 foreach ($terms['tags'] as $inputTerm) {
204 $this->applyTagSearch($entitySelect, $inputTerm);
208 foreach ($terms['filters'] as $filterTerm => $filterValue) {
209 $functionName = camel_case('filter_' . $filterTerm);
210 if (method_exists($this, $functionName)) {
211 $this->$functionName($entitySelect, $entity, $filterValue);
215 return $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, 'view');
220 * Parse a search string into components.
221 * @param $searchString
224 protected function parseSearchString($searchString)
234 'exact' => '/"(.*?)"/',
235 'tags' => '/\[(.*?)\]/',
236 'filters' => '/\{(.*?)\}/'
239 // Parse special terms
240 foreach ($patterns as $termType => $pattern) {
242 preg_match_all($pattern, $searchString, $matches);
243 if (count($matches) > 0) {
244 $terms[$termType] = $matches[1];
245 $searchString = preg_replace($pattern, '', $searchString);
249 // Parse standard terms
250 foreach (explode(' ', trim($searchString)) as $searchTerm) {
251 if ($searchTerm !== '') {
252 $terms['search'][] = $searchTerm;
256 // Split filter values out
258 foreach ($terms['filters'] as $filter) {
259 $explodedFilter = explode(':', $filter, 2);
260 $splitFilters[$explodedFilter[0]] = (count($explodedFilter) > 1) ? $explodedFilter[1] : '';
262 $terms['filters'] = $splitFilters;
268 * Get the available query operators as a regex escaped list.
271 protected function getRegexEscapedOperators()
273 $escapedOperators = [];
274 foreach ($this->queryOperators as $operator) {
275 $escapedOperators[] = preg_quote($operator);
277 return join('|', $escapedOperators);
281 * Apply a tag search term onto a entity query.
282 * @param \Illuminate\Database\Eloquent\Builder $query
283 * @param string $tagTerm
286 protected function applyTagSearch(\Illuminate\Database\Eloquent\Builder $query, $tagTerm)
288 preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
289 $query->whereHas('tags', function (\Illuminate\Database\Eloquent\Builder $query) use ($tagSplit) {
290 $tagName = $tagSplit[1];
291 $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
292 $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
293 $validOperator = in_array($tagOperator, $this->queryOperators);
294 if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
295 if (!empty($tagName)) {
296 $query->where('name', '=', $tagName);
298 if (is_numeric($tagValue) && $tagOperator !== 'like') {
299 // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
300 // search the value as a string which prevents being able to do number-based operations
301 // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
302 $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
303 $query->whereRaw("value ${tagOperator} ${tagValue}");
305 $query->where('value', $tagOperator, $tagValue);
308 $query->where('name', '=', $tagName);
315 * Get an entity instance via type.
319 protected function getEntity($type)
321 return $this->entities[strtolower($type)];
325 * Index the given entity.
326 * @param Entity $entity
328 public function indexEntity(Entity $entity)
330 $this->deleteEntityTerms($entity);
331 $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
332 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
333 $terms = array_merge($nameTerms, $bodyTerms);
334 foreach ($terms as $index => $term) {
335 $terms[$index]['entity_type'] = $entity->getMorphClass();
336 $terms[$index]['entity_id'] = $entity->id;
338 $this->searchTerm->newQuery()->insert($terms);
342 * Index multiple Entities at once
343 * @param Entity[] $entities
345 protected function indexEntities($entities)
348 foreach ($entities as $entity) {
349 $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
350 $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
351 foreach (array_merge($nameTerms, $bodyTerms) as $term) {
352 $term['entity_id'] = $entity->id;
353 $term['entity_type'] = $entity->getMorphClass();
358 $chunkedTerms = array_chunk($terms, 500);
359 foreach ($chunkedTerms as $termChunk) {
360 $this->searchTerm->newQuery()->insert($termChunk);
365 * Delete and re-index the terms for all entities in the system.
367 public function indexAllEntities()
369 $this->searchTerm->truncate();
371 // Chunk through all books
372 $this->book->chunk(1000, function ($books) {
373 $this->indexEntities($books);
376 // Chunk through all chapters
377 $this->chapter->chunk(1000, function ($chapters) {
378 $this->indexEntities($chapters);
381 // Chunk through all pages
382 $this->page->chunk(1000, function ($pages) {
383 $this->indexEntities($pages);
388 * Delete related Entity search terms.
389 * @param Entity $entity
391 public function deleteEntityTerms(Entity $entity)
393 $entity->searchTerms()->delete();
397 * Create a scored term array from the given text.
399 * @param float|int $scoreAdjustment
402 protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
404 $tokenMap = []; // {TextToken => OccurrenceCount}
405 $splitChars = " \n\t.,!?:;()[]{}<>`'\"";
406 $token = strtok($text, $splitChars);
408 while ($token !== false) {
409 if (!isset($tokenMap[$token])) {
410 $tokenMap[$token] = 0;
413 $token = strtok($splitChars);
417 foreach ($tokenMap as $token => $count) {
420 'score' => $count * $scoreAdjustment
430 * Custom entity search filters
433 protected function filterUpdatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
436 $date = date_create($input);
437 } catch (\Exception $e) {
440 $query->where('updated_at', '>=', $date);
443 protected function filterUpdatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
446 $date = date_create($input);
447 } catch (\Exception $e) {
450 $query->where('updated_at', '<', $date);
453 protected function filterCreatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
456 $date = date_create($input);
457 } catch (\Exception $e) {
460 $query->where('created_at', '>=', $date);
463 protected function filterCreatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
466 $date = date_create($input);
467 } catch (\Exception $e) {
470 $query->where('created_at', '<', $date);
473 protected function filterCreatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
475 if (!is_numeric($input) && $input !== 'me') {
478 if ($input === 'me') {
481 $query->where('created_by', '=', $input);
484 protected function filterUpdatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
486 if (!is_numeric($input) && $input !== 'me') {
489 if ($input === 'me') {
492 $query->where('updated_by', '=', $input);
495 protected function filterInName(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
497 $query->where('name', 'like', '%' .$input. '%');
500 protected function filterInTitle(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
502 $this->filterInName($query, $model, $input);
505 protected function filterInBody(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
507 $query->where($model->textField, 'like', '%' .$input. '%');
510 protected function filterIsRestricted(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
512 $query->where('restricted', '=', true);
515 protected function filterViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
517 $query->whereHas('views', function ($query) {
518 $query->where('user_id', '=', user()->id);
522 protected function filterNotViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
524 $query->whereDoesntHave('views', function ($query) {
525 $query->where('user_id', '=', user()->id);
529 protected function filterSortBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
531 $functionName = camel_case('sort_by_' . $input);
532 if (method_exists($this, $functionName)) {
533 $this->$functionName($query, $model);
539 * Sorting filter options
542 protected function sortByLastCommented(\Illuminate\Database\Eloquent\Builder $query, Entity $model)
544 $commentsTable = $this->db->getTablePrefix() . 'comments';
545 $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
546 $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');
548 $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');