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