]> BookStack Code Mirror - bookstack/blob - app/Services/SearchService.php
French translation update
[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, $action = 'view')
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, $action);
91             $entityTotal = $this->searchEntityTable($terms, $entityType, $page, $count, $action, 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 string $action
151      * @param bool $getCount Return the total count of the search
152      * @return \Illuminate\Database\Eloquent\Collection|int|static[]
153      */
154     public function searchEntityTable($terms, $entityType = 'page', $page = 1, $count = 20, $action = 'view', $getCount = false)
155     {
156         $query = $this->buildEntitySearchQuery($terms, $entityType, $action);
157         if ($getCount) {
158             return $query->count();
159         }
160
161         $query = $query->skip(($page-1) * $count)->take($count);
162         return $query->get();
163     }
164
165     /**
166      * Create a search query for an entity
167      * @param array $terms
168      * @param string $entityType
169      * @param string $action
170      * @return \Illuminate\Database\Eloquent\Builder
171      */
172     protected function buildEntitySearchQuery($terms, $entityType = 'page', $action = 'view')
173     {
174         $entity = $this->getEntity($entityType);
175         $entitySelect = $entity->newQuery();
176
177         // Handle normal search terms
178         if (count($terms['search']) > 0) {
179             $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', \DB::raw('SUM(score) as score'));
180             $subQuery->where('entity_type', '=', 'BookStack\\' . ucfirst($entityType));
181             $subQuery->where(function (Builder $query) use ($terms) {
182                 foreach ($terms['search'] as $inputTerm) {
183                     $query->orWhere('term', 'like', $inputTerm .'%');
184                 }
185             })->groupBy('entity_type', 'entity_id');
186             $entitySelect->join(\DB::raw('(' . $subQuery->toSql() . ') as s'), function (JoinClause $join) {
187                 $join->on('id', '=', 'entity_id');
188             })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
189             $entitySelect->mergeBindings($subQuery);
190         }
191
192         // Handle exact term matching
193         if (count($terms['exact']) > 0) {
194             $entitySelect->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($terms, $entity) {
195                 foreach ($terms['exact'] as $inputTerm) {
196                     $query->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($inputTerm, $entity) {
197                         $query->where('name', 'like', '%'.$inputTerm .'%')
198                             ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
199                     });
200                 }
201             });
202         }
203
204         // Handle tag searches
205         foreach ($terms['tags'] as $inputTerm) {
206             $this->applyTagSearch($entitySelect, $inputTerm);
207         }
208
209         // Handle filters
210         foreach ($terms['filters'] as $filterTerm => $filterValue) {
211             $functionName = camel_case('filter_' . $filterTerm);
212             if (method_exists($this, $functionName)) {
213                 $this->$functionName($entitySelect, $entity, $filterValue);
214             }
215         }
216
217         return $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, $action);
218     }
219
220
221     /**
222      * Parse a search string into components.
223      * @param $searchString
224      * @return array
225      */
226     protected function parseSearchString($searchString)
227     {
228         $terms = [
229             'search' => [],
230             'exact' => [],
231             'tags' => [],
232             'filters' => []
233         ];
234
235         $patterns = [
236             'exact' => '/"(.*?)"/',
237             'tags' => '/\[(.*?)\]/',
238             'filters' => '/\{(.*?)\}/'
239         ];
240
241         // Parse special terms
242         foreach ($patterns as $termType => $pattern) {
243             $matches = [];
244             preg_match_all($pattern, $searchString, $matches);
245             if (count($matches) > 0) {
246                 $terms[$termType] = $matches[1];
247                 $searchString = preg_replace($pattern, '', $searchString);
248             }
249         }
250
251         // Parse standard terms
252         foreach (explode(' ', trim($searchString)) as $searchTerm) {
253             if ($searchTerm !== '') {
254                 $terms['search'][] = $searchTerm;
255             }
256         }
257
258         // Split filter values out
259         $splitFilters = [];
260         foreach ($terms['filters'] as $filter) {
261             $explodedFilter = explode(':', $filter, 2);
262             $splitFilters[$explodedFilter[0]] = (count($explodedFilter) > 1) ? $explodedFilter[1] : '';
263         }
264         $terms['filters'] = $splitFilters;
265
266         return $terms;
267     }
268
269     /**
270      * Get the available query operators as a regex escaped list.
271      * @return mixed
272      */
273     protected function getRegexEscapedOperators()
274     {
275         $escapedOperators = [];
276         foreach ($this->queryOperators as $operator) {
277             $escapedOperators[] = preg_quote($operator);
278         }
279         return join('|', $escapedOperators);
280     }
281
282     /**
283      * Apply a tag search term onto a entity query.
284      * @param \Illuminate\Database\Eloquent\Builder $query
285      * @param string $tagTerm
286      * @return mixed
287      */
288     protected function applyTagSearch(\Illuminate\Database\Eloquent\Builder $query, $tagTerm)
289     {
290         preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
291         $query->whereHas('tags', function (\Illuminate\Database\Eloquent\Builder $query) use ($tagSplit) {
292             $tagName = $tagSplit[1];
293             $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
294             $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
295             $validOperator = in_array($tagOperator, $this->queryOperators);
296             if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
297                 if (!empty($tagName)) {
298                     $query->where('name', '=', $tagName);
299                 }
300                 if (is_numeric($tagValue) && $tagOperator !== 'like') {
301                     // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
302                     // search the value as a string which prevents being able to do number-based operations
303                     // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
304                     $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
305                     $query->whereRaw("value ${tagOperator} ${tagValue}");
306                 } else {
307                     $query->where('value', $tagOperator, $tagValue);
308                 }
309             } else {
310                 $query->where('name', '=', $tagName);
311             }
312         });
313         return $query;
314     }
315
316     /**
317      * Get an entity instance via type.
318      * @param $type
319      * @return Entity
320      */
321     protected function getEntity($type)
322     {
323         return $this->entities[strtolower($type)];
324     }
325
326     /**
327      * Index the given entity.
328      * @param Entity $entity
329      */
330     public function indexEntity(Entity $entity)
331     {
332         $this->deleteEntityTerms($entity);
333         $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
334         $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
335         $terms = array_merge($nameTerms, $bodyTerms);
336         foreach ($terms as $index => $term) {
337             $terms[$index]['entity_type'] = $entity->getMorphClass();
338             $terms[$index]['entity_id'] = $entity->id;
339         }
340         $this->searchTerm->newQuery()->insert($terms);
341     }
342
343     /**
344      * Index multiple Entities at once
345      * @param Entity[] $entities
346      */
347     protected function indexEntities($entities)
348     {
349         $terms = [];
350         foreach ($entities as $entity) {
351             $nameTerms = $this->generateTermArrayFromText($entity->name, 5 * $entity->searchFactor);
352             $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1 * $entity->searchFactor);
353             foreach (array_merge($nameTerms, $bodyTerms) as $term) {
354                 $term['entity_id'] = $entity->id;
355                 $term['entity_type'] = $entity->getMorphClass();
356                 $terms[] = $term;
357             }
358         }
359
360         $chunkedTerms = array_chunk($terms, 500);
361         foreach ($chunkedTerms as $termChunk) {
362             $this->searchTerm->newQuery()->insert($termChunk);
363         }
364     }
365
366     /**
367      * Delete and re-index the terms for all entities in the system.
368      */
369     public function indexAllEntities()
370     {
371         $this->searchTerm->truncate();
372
373         // Chunk through all books
374         $this->book->chunk(1000, function ($books) {
375             $this->indexEntities($books);
376         });
377
378         // Chunk through all chapters
379         $this->chapter->chunk(1000, function ($chapters) {
380             $this->indexEntities($chapters);
381         });
382
383         // Chunk through all pages
384         $this->page->chunk(1000, function ($pages) {
385             $this->indexEntities($pages);
386         });
387     }
388
389     /**
390      * Delete related Entity search terms.
391      * @param Entity $entity
392      */
393     public function deleteEntityTerms(Entity $entity)
394     {
395         $entity->searchTerms()->delete();
396     }
397
398     /**
399      * Create a scored term array from the given text.
400      * @param $text
401      * @param float|int $scoreAdjustment
402      * @return array
403      */
404     protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
405     {
406         $tokenMap = []; // {TextToken => OccurrenceCount}
407         $splitChars = " \n\t.,!?:;()[]{}<>`'\"";
408         $token = strtok($text, $splitChars);
409
410         while ($token !== false) {
411             if (!isset($tokenMap[$token])) {
412                 $tokenMap[$token] = 0;
413             }
414             $tokenMap[$token]++;
415             $token = strtok($splitChars);
416         }
417
418         $terms = [];
419         foreach ($tokenMap as $token => $count) {
420             $terms[] = [
421                 'term' => $token,
422                 'score' => $count * $scoreAdjustment
423             ];
424         }
425         return $terms;
426     }
427
428
429
430
431     /**
432      * Custom entity search filters
433      */
434
435     protected function filterUpdatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
436     {
437         try {
438             $date = date_create($input);
439         } catch (\Exception $e) {
440             return;
441         }
442         $query->where('updated_at', '>=', $date);
443     }
444
445     protected function filterUpdatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
446     {
447         try {
448             $date = date_create($input);
449         } catch (\Exception $e) {
450             return;
451         }
452         $query->where('updated_at', '<', $date);
453     }
454
455     protected function filterCreatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
456     {
457         try {
458             $date = date_create($input);
459         } catch (\Exception $e) {
460             return;
461         }
462         $query->where('created_at', '>=', $date);
463     }
464
465     protected function filterCreatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
466     {
467         try {
468             $date = date_create($input);
469         } catch (\Exception $e) {
470             return;
471         }
472         $query->where('created_at', '<', $date);
473     }
474
475     protected function filterCreatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
476     {
477         if (!is_numeric($input) && $input !== 'me') {
478             return;
479         }
480         if ($input === 'me') {
481             $input = user()->id;
482         }
483         $query->where('created_by', '=', $input);
484     }
485
486     protected function filterUpdatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
487     {
488         if (!is_numeric($input) && $input !== 'me') {
489             return;
490         }
491         if ($input === 'me') {
492             $input = user()->id;
493         }
494         $query->where('updated_by', '=', $input);
495     }
496
497     protected function filterInName(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
498     {
499         $query->where('name', 'like', '%' .$input. '%');
500     }
501
502     protected function filterInTitle(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
503     {
504         $this->filterInName($query, $model, $input);
505     }
506
507     protected function filterInBody(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
508     {
509         $query->where($model->textField, 'like', '%' .$input. '%');
510     }
511
512     protected function filterIsRestricted(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
513     {
514         $query->where('restricted', '=', true);
515     }
516
517     protected function filterViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
518     {
519         $query->whereHas('views', function ($query) {
520             $query->where('user_id', '=', user()->id);
521         });
522     }
523
524     protected function filterNotViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
525     {
526         $query->whereDoesntHave('views', function ($query) {
527             $query->where('user_id', '=', user()->id);
528         });
529     }
530
531     protected function filterSortBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
532     {
533         $functionName = camel_case('sort_by_' . $input);
534         if (method_exists($this, $functionName)) {
535             $this->$functionName($query, $model);
536         }
537     }
538
539
540     /**
541      * Sorting filter options
542      */
543
544     protected function sortByLastCommented(\Illuminate\Database\Eloquent\Builder $query, Entity $model)
545     {
546         $commentsTable = $this->db->getTablePrefix() . 'comments';
547         $morphClass = str_replace('\\', '\\\\', $model->getMorphClass());
548         $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');
549
550         $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');
551     }
552 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.