]> BookStack Code Mirror - bookstack/blob - app/Services/SearchService.php
Update german translation
[bookstack] / app / Services / SearchService.php
1 <?php namespace BookStack\Services;
2
3 use BookStack\Book;
4 use BookStack\Bookshelf;
5 use BookStack\Chapter;
6 use BookStack\Entity;
7 use BookStack\Page;
8 use BookStack\SearchTerm;
9 use Illuminate\Database\Connection;
10 use Illuminate\Database\Query\Builder;
11 use Illuminate\Database\Query\JoinClause;
12 use Illuminate\Support\Collection;
13
14 class SearchService
15 {
16     protected $searchTerm;
17     protected $bookshelf;
18     protected $book;
19     protected $chapter;
20     protected $page;
21     protected $db;
22     protected $permissionService;
23
24     /**
25      * @var Entity[]
26      */
27     protected $entities;
28
29     /**
30      * Acceptable operators to be used in a query
31      * @var array
32      */
33     protected $queryOperators = ['<=', '>=', '=', '<', '>', 'like', '!='];
34
35     /**
36      * SearchService constructor.
37      * @param SearchTerm $searchTerm
38      * @param Bookshelf $bookshelf
39      * @param Book $book
40      * @param Chapter $chapter
41      * @param Page $page
42      * @param Connection $db
43      * @param PermissionService $permissionService
44      */
45     public function __construct(SearchTerm $searchTerm, Bookshelf $bookshelf, Book $book, Chapter $chapter, Page $page, Connection $db, PermissionService $permissionService)
46     {
47         $this->searchTerm = $searchTerm;
48         $this->bookshelf = $bookshelf;
49         $this->book = $book;
50         $this->chapter = $chapter;
51         $this->page = $page;
52         $this->db = $db;
53         $this->entities = [
54             'bookshelf' => $this->bookshelf,
55             'page' => $this->page,
56             'chapter' => $this->chapter,
57             'book' => $this->book
58         ];
59         $this->permissionService = $permissionService;
60     }
61
62     /**
63      * Set the database connection
64      * @param Connection $connection
65      */
66     public function setConnection(Connection $connection)
67     {
68         $this->db = $connection;
69     }
70
71     /**
72      * Search all entities in the system.
73      * @param string $searchString
74      * @param string $entityType
75      * @param int $page
76      * @param int $count - Count of each entity to search, Total returned could can be larger and not guaranteed.
77      * @param string $action
78      * @return array[int, Collection];
79      */
80     public function searchEntities($searchString, $entityType = 'all', $page = 1, $count = 20, $action = 'view')
81     {
82         $terms = $this->parseSearchString($searchString);
83         $entityTypes = array_keys($this->entities);
84         $entityTypesToSearch = $entityTypes;
85
86         if ($entityType !== 'all') {
87             $entityTypesToSearch = $entityType;
88         } else if (isset($terms['filters']['type'])) {
89             $entityTypesToSearch = explode('|', $terms['filters']['type']);
90         }
91
92         $results = collect();
93         $total = 0;
94         $hasMore = false;
95
96         foreach ($entityTypesToSearch as $entityType) {
97             if (!in_array($entityType, $entityTypes)) {
98                 continue;
99             }
100             $search = $this->searchEntityTable($terms, $entityType, $page, $count, $action);
101             $entityTotal = $this->searchEntityTable($terms, $entityType, $page, $count, $action, true);
102             if ($entityTotal > $page * $count) {
103                 $hasMore = true;
104             }
105             $total += $entityTotal;
106             $results = $results->merge($search);
107         }
108
109         return [
110             'total' => $total,
111             'count' => count($results),
112             'has_more' => $hasMore,
113             'results' => $results->sortByDesc('score')->values()
114         ];
115     }
116
117
118     /**
119      * Search a book for entities
120      * @param integer $bookId
121      * @param string $searchString
122      * @return Collection
123      */
124     public function searchBook($bookId, $searchString)
125     {
126         $terms = $this->parseSearchString($searchString);
127         $entityTypes = ['page', 'chapter'];
128         $entityTypesToSearch = isset($terms['filters']['type']) ? explode('|', $terms['filters']['type']) : $entityTypes;
129
130         $results = collect();
131         foreach ($entityTypesToSearch as $entityType) {
132             if (!in_array($entityType, $entityTypes)) {
133                 continue;
134             }
135             $search = $this->buildEntitySearchQuery($terms, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
136             $results = $results->merge($search);
137         }
138         return $results->sortByDesc('score')->take(20);
139     }
140
141     /**
142      * Search a book for entities
143      * @param integer $chapterId
144      * @param string $searchString
145      * @return Collection
146      */
147     public function searchChapter($chapterId, $searchString)
148     {
149         $terms = $this->parseSearchString($searchString);
150         $pages = $this->buildEntitySearchQuery($terms, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
151         return $pages->sortByDesc('score');
152     }
153
154     /**
155      * Search across a particular entity type.
156      * @param array $terms
157      * @param string $entityType
158      * @param int $page
159      * @param int $count
160      * @param string $action
161      * @param bool $getCount Return the total count of the search
162      * @return \Illuminate\Database\Eloquent\Collection|int|static[]
163      */
164     public function searchEntityTable($terms, $entityType = 'page', $page = 1, $count = 20, $action = 'view', $getCount = false)
165     {
166         $query = $this->buildEntitySearchQuery($terms, $entityType, $action);
167         if ($getCount) {
168             return $query->count();
169         }
170
171         $query = $query->skip(($page-1) * $count)->take($count);
172         return $query->get();
173     }
174
175     /**
176      * Create a search query for an entity
177      * @param array $terms
178      * @param string $entityType
179      * @param string $action
180      * @return \Illuminate\Database\Eloquent\Builder
181      */
182     protected function buildEntitySearchQuery($terms, $entityType = 'page', $action = 'view')
183     {
184         $entity = $this->getEntity($entityType);
185         $entitySelect = $entity->newQuery();
186
187         // Handle normal search terms
188         if (count($terms['search']) > 0) {
189             $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', \DB::raw('SUM(score) as score'));
190             $subQuery->where('entity_type', '=', 'BookStack\\' . ucfirst($entityType));
191             $subQuery->where(function (Builder $query) use ($terms) {
192                 foreach ($terms['search'] as $inputTerm) {
193                     $query->orWhere('term', 'like', $inputTerm .'%');
194                 }
195             })->groupBy('entity_type', 'entity_id');
196             $entitySelect->join(\DB::raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) {
197                 $join->on('id', '=', 'entity_id');
198             })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
199             $entitySelect->mergeBindings($subQuery);
200         }
201
202         // Handle exact term matching
203         if (count($terms['exact']) > 0) {
204             $entitySelect->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($terms, $entity) {
205                 foreach ($terms['exact'] as $inputTerm) {
206                     $query->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($inputTerm, $entity) {
207                         $query->where('name', 'like', '%'.$inputTerm .'%')
208                             ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
209                     });
210                 }
211             });
212         }
213
214         // Handle tag searches
215         foreach ($terms['tags'] as $inputTerm) {
216             $this->applyTagSearch($entitySelect, $inputTerm);
217         }
218
219         // Handle filters
220         foreach ($terms['filters'] as $filterTerm => $filterValue) {
221             $functionName = camel_case('filter_' . $filterTerm);
222             if (method_exists($this, $functionName)) {
223                 $this->$functionName($entitySelect, $entity, $filterValue);
224             }
225         }
226
227         return $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, $action);
228     }
229
230
231     /**
232      * Parse a search string into components.
233      * @param $searchString
234      * @return array
235      */
236     protected function parseSearchString($searchString)
237     {
238         $terms = [
239             'search' => [],
240             'exact' => [],
241             'tags' => [],
242             'filters' => []
243         ];
244
245         $patterns = [
246             'exact' => '/"(.*?)"/',
247             'tags' => '/\[(.*?)\]/',
248             'filters' => '/\{(.*?)\}/'
249         ];
250
251         // Parse special terms
252         foreach ($patterns as $termType => $pattern) {
253             $matches = [];
254             preg_match_all($pattern, $searchString, $matches);
255             if (count($matches) > 0) {
256                 $terms[$termType] = $matches[1];
257                 $searchString = preg_replace($pattern, '', $searchString);
258             }
259         }
260
261         // Parse standard terms
262         foreach (explode(' ', trim($searchString)) as $searchTerm) {
263             if ($searchTerm !== '') {
264                 $terms['search'][] = $searchTerm;
265             }
266         }
267
268         // Split filter values out
269         $splitFilters = [];
270         foreach ($terms['filters'] as $filter) {
271             $explodedFilter = explode(':', $filter, 2);
272             $splitFilters[$explodedFilter[0]] = (count($explodedFilter) > 1) ? $explodedFilter[1] : '';
273         }
274         $terms['filters'] = $splitFilters;
275
276         return $terms;
277     }
278
279     /**
280      * Get the available query operators as a regex escaped list.
281      * @return mixed
282      */
283     protected function getRegexEscapedOperators()
284     {
285         $escapedOperators = [];
286         foreach ($this->queryOperators as $operator) {
287             $escapedOperators[] = preg_quote($operator);
288         }
289         return join('|', $escapedOperators);
290     }
291
292     /**
293      * Apply a tag search term onto a entity query.
294      * @param \Illuminate\Database\Eloquent\Builder $query
295      * @param string $tagTerm
296      * @return mixed
297      */
298     protected function applyTagSearch(\Illuminate\Database\Eloquent\Builder $query, $tagTerm)
299     {
300         preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
301         $query->whereHas('tags', function (\Illuminate\Database\Eloquent\Builder $query) use ($tagSplit) {
302             $tagName = $tagSplit[1];
303             $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
304             $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
305             $validOperator = in_array($tagOperator, $this->queryOperators);
306             if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
307                 if (!empty($tagName)) {
308                     $query->where('name', '=', $tagName);
309                 }
310                 if (is_numeric($tagValue) && $tagOperator !== 'like') {
311                     // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
312                     // search the value as a string which prevents being able to do number-based operations
313                     // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
314                     $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
315                     $query->whereRaw("value ${tagOperator} ${tagValue}");
316                 } else {
317                     $query->where('value', $tagOperator, $tagValue);
318                 }
319             } else {
320                 $query->where('name', '=', $tagName);
321             }
322         });
323         return $query;
324     }
325
326     /**
327      * Get an entity instance via type.
328      * @param $type
329      * @return Entity
330      */
331     protected function getEntity($type)
332     {
333         return $this->entities[strtolower($type)];
334     }
335
336     /**
337      * Index the given entity.
338      * @param Entity $entity
339      */
340     public function indexEntity(Entity $entity)
341     {
342         $this->deleteEntityTerms($entity);
343         $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
344         $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
345         $terms = array_merge($nameTerms, $bodyTerms);
346         foreach ($terms as $index => $term) {
347             $terms[$index]['entity_type'] = $entity->getMorphClass();
348             $terms[$index]['entity_id'] = $entity->id;
349         }
350         $this->searchTerm->newQuery()->insert($terms);
351     }
352
353     /**
354      * Index multiple Entities at once
355      * @param Entity[] $entities
356      */
357     protected function indexEntities($entities)
358     {
359         $terms = [];
360         foreach ($entities as $entity) {
361             $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
362             $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
363             foreach (array_merge($nameTerms, $bodyTerms) as $term) {
364                 $term['entity_id'] = $entity->id;
365                 $term['entity_type'] = $entity->getMorphClass();
366                 $terms[] = $term;
367             }
368         }
369
370         $chunkedTerms = array_chunk($terms, 500);
371         foreach ($chunkedTerms as $termChunk) {
372             $this->searchTerm->newQuery()->insert($termChunk);
373         }
374     }
375
376     /**
377      * Delete and re-index the terms for all entities in the system.
378      */
379     public function indexAllEntities()
380     {
381         $this->searchTerm->truncate();
382
383         foreach ($this->entities as $entityModel) {
384             $selectFields = ['id', 'name', $entityModel->textField];
385             $entityModel->newQuery()->select($selectFields)->chunk(1000, function ($entities) {
386                 $this->indexEntities($entities);
387             });
388         }
389     }
390
391     /**
392      * Delete related Entity search terms.
393      * @param Entity $entity
394      */
395     public function deleteEntityTerms(Entity $entity)
396     {
397         $entity->searchTerms()->delete();
398     }
399
400     /**
401      * Create a scored term array from the given text.
402      * @param $text
403      * @param float|int $scoreAdjustment
404      * @return array
405      */
406     protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
407     {
408         $tokenMap = []; // {TextToken => OccurrenceCount}
409         $splitChars = " \n\t.,!?:;()[]{}<>`'\"";
410         $token = strtok($text, $splitChars);
411
412         while ($token !== false) {
413             if (!isset($tokenMap[$token])) {
414                 $tokenMap[$token] = 0;
415             }
416             $tokenMap[$token]++;
417             $token = strtok($splitChars);
418         }
419
420         $terms = [];
421         foreach ($tokenMap as $token => $count) {
422             $terms[] = [
423                 'term' => $token,
424                 'score' => $count * $scoreAdjustment
425             ];
426         }
427         return $terms;
428     }
429
430
431
432
433     /**
434      * Custom entity search filters
435      */
436
437     protected function filterUpdatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
438     {
439         try {
440             $date = date_create($input);
441         } catch (\Exception $e) {
442             return;
443         }
444         $query->where('updated_at', '>=', $date);
445     }
446
447     protected function filterUpdatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
448     {
449         try {
450             $date = date_create($input);
451         } catch (\Exception $e) {
452             return;
453         }
454         $query->where('updated_at', '<', $date);
455     }
456
457     protected function filterCreatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
458     {
459         try {
460             $date = date_create($input);
461         } catch (\Exception $e) {
462             return;
463         }
464         $query->where('created_at', '>=', $date);
465     }
466
467     protected function filterCreatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
468     {
469         try {
470             $date = date_create($input);
471         } catch (\Exception $e) {
472             return;
473         }
474         $query->where('created_at', '<', $date);
475     }
476
477     protected function filterCreatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
478     {
479         if (!is_numeric($input) && $input !== 'me') {
480             return;
481         }
482         if ($input === 'me') {
483             $input = user()->id;
484         }
485         $query->where('created_by', '=', $input);
486     }
487
488     protected function filterUpdatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
489     {
490         if (!is_numeric($input) && $input !== 'me') {
491             return;
492         }
493         if ($input === 'me') {
494             $input = user()->id;
495         }
496         $query->where('updated_by', '=', $input);
497     }
498
499     protected function filterInName(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
500     {
501         $query->where('name', 'like', '%' .$input. '%');
502     }
503
504     protected function filterInTitle(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
505     {
506         $this->filterInName($query, $model, $input);
507     }
508
509     protected function filterInBody(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
510     {
511         $query->where($model->textField, 'like', '%' .$input. '%');
512     }
513
514     protected function filterIsRestricted(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
515     {
516         $query->where('restricted', '=', true);
517     }
518
519     protected function filterViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
520     {
521         $query->whereHas('views', function ($query) {
522             $query->where('user_id', '=', user()->id);
523         });
524     }
525
526     protected function filterNotViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
527     {
528         $query->whereDoesntHave('views', function ($query) {
529             $query->where('user_id', '=', user()->id);
530         });
531     }
532
533     protected function filterSortBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
534     {
535         $functionName = camel_case('sort_by_' . $input);
536         if (method_exists($this, $functionName)) {
537             $this->$functionName($query, $model);
538         }
539     }
540
541
542     /**
543      * Sorting filter options
544      */
545
546     protected function sortByLastCommented(\Illuminate\Database\Eloquent\Builder $query, Entity $model)
547     {
548         $commentsTable = $this->db->getTablePrefix() . 'comments';
549         $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
550         $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');
551
552         $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');
553     }
554 }