]> BookStack Code Mirror - bookstack/blob - app/Services/SearchService.php
cb445eed1e5242fa3cc1d1ff92740e9efb13a21d
[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
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
85         foreach ($entityTypesToSearch as $entityType) {
86             if (!in_array($entityType, $entityTypes)) {
87                 continue;
88             }
89             $search = $this->searchEntityTable($terms, $entityType, $page, $count + 1);
90             $total += $this->searchEntityTable($terms, $entityType, $page, $count + 1, true);
91             $results = $results->merge($search);
92         }
93
94         return [
95             'total' => $total,
96             'count' => count($results),
97             'has_more' => $results->count() > $count,
98             'results' => $results->sortByDesc('score')->slice(0, $count)->values()
99         ];
100     }
101
102
103     /**
104      * Search a book for entities
105      * @param integer $bookId
106      * @param string $searchString
107      * @return Collection
108      */
109     public function searchBook($bookId, $searchString)
110     {
111         $terms = $this->parseSearchString($searchString);
112         $entityTypes = ['page', 'chapter'];
113         $entityTypesToSearch = isset($terms['filters']['type']) ? explode('|', $terms['filters']['type']) : $entityTypes;
114
115         $results = collect();
116         foreach ($entityTypesToSearch as $entityType) {
117             if (!in_array($entityType, $entityTypes)) {
118                 continue;
119             }
120             $search = $this->buildEntitySearchQuery($terms, $entityType)->where('book_id', '=', $bookId)->take(20)->get();
121             $results = $results->merge($search);
122         }
123         return $results->sortByDesc('score')->take(20);
124     }
125
126     /**
127      * Search a book for entities
128      * @param integer $chapterId
129      * @param string $searchString
130      * @return Collection
131      */
132     public function searchChapter($chapterId, $searchString)
133     {
134         $terms = $this->parseSearchString($searchString);
135         $pages = $this->buildEntitySearchQuery($terms, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
136         return $pages->sortByDesc('score');
137     }
138
139     /**
140      * Search across a particular entity type.
141      * @param array $terms
142      * @param string $entityType
143      * @param int $page
144      * @param int $count
145      * @param bool $getCount Return the total count of the search
146      * @return \Illuminate\Database\Eloquent\Collection|int|static[]
147      */
148     public function searchEntityTable($terms, $entityType = 'page', $page = 1, $count = 20, $getCount = false)
149     {
150         $query = $this->buildEntitySearchQuery($terms, $entityType);
151         if ($getCount) {
152             return $query->count();
153         }
154
155         $query = $query->skip(($page-1) * $count)->take($count);
156         return $query->get();
157     }
158
159     /**
160      * Create a search query for an entity
161      * @param array $terms
162      * @param string $entityType
163      * @return \Illuminate\Database\Eloquent\Builder
164      */
165     protected function buildEntitySearchQuery($terms, $entityType = 'page')
166     {
167         $entity = $this->getEntity($entityType);
168         $entitySelect = $entity->newQuery();
169
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 .'%');
177                 }
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);
183         }
184
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 .'%');
192                     });
193                 }
194             });
195         }
196
197         // Handle tag searches
198         foreach ($terms['tags'] as $inputTerm) {
199             $this->applyTagSearch($entitySelect, $inputTerm);
200         }
201
202         // Handle filters
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);
207             }
208         }
209
210         return $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, 'view');
211     }
212
213
214     /**
215      * Parse a search string into components.
216      * @param $searchString
217      * @return array
218      */
219     protected function parseSearchString($searchString)
220     {
221         $terms = [
222             'search' => [],
223             'exact' => [],
224             'tags' => [],
225             'filters' => []
226         ];
227
228         $patterns = [
229             'exact' => '/"(.*?)"/',
230             'tags' => '/\[(.*?)\]/',
231             'filters' => '/\{(.*?)\}/'
232         ];
233
234         // Parse special terms
235         foreach ($patterns as $termType => $pattern) {
236             $matches = [];
237             preg_match_all($pattern, $searchString, $matches);
238             if (count($matches) > 0) {
239                 $terms[$termType] = $matches[1];
240                 $searchString = preg_replace($pattern, '', $searchString);
241             }
242         }
243
244         // Parse standard terms
245         foreach (explode(' ', trim($searchString)) as $searchTerm) {
246             if ($searchTerm !== '') {
247                 $terms['search'][] = $searchTerm;
248             }
249         }
250
251         // Split filter values out
252         $splitFilters = [];
253         foreach ($terms['filters'] as $filter) {
254             $explodedFilter = explode(':', $filter, 2);
255             $splitFilters[$explodedFilter[0]] = (count($explodedFilter) > 1) ? $explodedFilter[1] : '';
256         }
257         $terms['filters'] = $splitFilters;
258
259         return $terms;
260     }
261
262     /**
263      * Get the available query operators as a regex escaped list.
264      * @return mixed
265      */
266     protected function getRegexEscapedOperators()
267     {
268         $escapedOperators = [];
269         foreach ($this->queryOperators as $operator) {
270             $escapedOperators[] = preg_quote($operator);
271         }
272         return join('|', $escapedOperators);
273     }
274
275     /**
276      * Apply a tag search term onto a entity query.
277      * @param \Illuminate\Database\Eloquent\Builder $query
278      * @param string $tagTerm
279      * @return mixed
280      */
281     protected function applyTagSearch(\Illuminate\Database\Eloquent\Builder $query, $tagTerm)
282     {
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);
292                 }
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}");
299                 } else {
300                     $query->where('value', $tagOperator, $tagValue);
301                 }
302             } else {
303                 $query->where('name', '=', $tagName);
304             }
305         });
306         return $query;
307     }
308
309     /**
310      * Get an entity instance via type.
311      * @param $type
312      * @return Entity
313      */
314     protected function getEntity($type)
315     {
316         return $this->entities[strtolower($type)];
317     }
318
319     /**
320      * Index the given entity.
321      * @param Entity $entity
322      */
323     public function indexEntity(Entity $entity)
324     {
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;
332         }
333         $this->searchTerm->newQuery()->insert($terms);
334     }
335
336     /**
337      * Index multiple Entities at once
338      * @param Entity[] $entities
339      */
340     protected function indexEntities($entities)
341     {
342         $terms = [];
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();
349                 $terms[] = $term;
350             }
351         }
352
353         $chunkedTerms = array_chunk($terms, 500);
354         foreach ($chunkedTerms as $termChunk) {
355             $this->searchTerm->newQuery()->insert($termChunk);
356         }
357     }
358
359     /**
360      * Delete and re-index the terms for all entities in the system.
361      */
362     public function indexAllEntities()
363     {
364         $this->searchTerm->truncate();
365
366         // Chunk through all books
367         $this->book->chunk(1000, function ($books) {
368             $this->indexEntities($books);
369         });
370
371         // Chunk through all chapters
372         $this->chapter->chunk(1000, function ($chapters) {
373             $this->indexEntities($chapters);
374         });
375
376         // Chunk through all pages
377         $this->page->chunk(1000, function ($pages) {
378             $this->indexEntities($pages);
379         });
380     }
381
382     /**
383      * Delete related Entity search terms.
384      * @param Entity $entity
385      */
386     public function deleteEntityTerms(Entity $entity)
387     {
388         $entity->searchTerms()->delete();
389     }
390
391     /**
392      * Create a scored term array from the given text.
393      * @param $text
394      * @param float|int $scoreAdjustment
395      * @return array
396      */
397     protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
398     {
399         $tokenMap = []; // {TextToken => OccurrenceCount}
400         $splitChars = " \n\t.,!?:;()[]{}<>`'\"";
401         $token = strtok($text, $splitChars);
402
403         while ($token !== false) {
404             if (!isset($tokenMap[$token])) {
405                 $tokenMap[$token] = 0;
406             }
407             $tokenMap[$token]++;
408             $token = strtok($splitChars);
409         }
410
411         $terms = [];
412         foreach ($tokenMap as $token => $count) {
413             $terms[] = [
414                 'term' => $token,
415                 'score' => $count * $scoreAdjustment
416             ];
417         }
418         return $terms;
419     }
420
421
422
423
424     /**
425      * Custom entity search filters
426      */
427
428     protected function filterUpdatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
429     {
430         try {
431             $date = date_create($input);
432         } catch (\Exception $e) {
433             return;
434         }
435         $query->where('updated_at', '>=', $date);
436     }
437
438     protected function filterUpdatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
439     {
440         try {
441             $date = date_create($input);
442         } catch (\Exception $e) {
443             return;
444         }
445         $query->where('updated_at', '<', $date);
446     }
447
448     protected function filterCreatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
449     {
450         try {
451             $date = date_create($input);
452         } catch (\Exception $e) {
453             return;
454         }
455         $query->where('created_at', '>=', $date);
456     }
457
458     protected function filterCreatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
459     {
460         try {
461             $date = date_create($input);
462         } catch (\Exception $e) {
463             return;
464         }
465         $query->where('created_at', '<', $date);
466     }
467
468     protected function filterCreatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
469     {
470         if (!is_numeric($input) && $input !== 'me') {
471             return;
472         }
473         if ($input === 'me') {
474             $input = user()->id;
475         }
476         $query->where('created_by', '=', $input);
477     }
478
479     protected function filterUpdatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
480     {
481         if (!is_numeric($input) && $input !== 'me') {
482             return;
483         }
484         if ($input === 'me') {
485             $input = user()->id;
486         }
487         $query->where('updated_by', '=', $input);
488     }
489
490     protected function filterInName(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
491     {
492         $query->where('name', 'like', '%' .$input. '%');
493     }
494
495     protected function filterInTitle(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
496     {
497         $this->filterInName($query, $model, $input);
498     }
499
500     protected function filterInBody(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
501     {
502         $query->where($model->textField, 'like', '%' .$input. '%');
503     }
504
505     protected function filterIsRestricted(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
506     {
507         $query->where('restricted', '=', true);
508     }
509
510     protected function filterViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
511     {
512         $query->whereHas('views', function ($query) {
513             $query->where('user_id', '=', user()->id);
514         });
515     }
516
517     protected function filterNotViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
518     {
519         $query->whereDoesntHave('views', function ($query) {
520             $query->where('user_id', '=', user()->id);
521         });
522     }
523
524     protected function filterSortBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
525     {
526         $functionName = camel_case('sort_by_' . $input);
527         if (method_exists($this, $functionName)) {
528             $this->$functionName($query, $model);
529         }
530     }
531
532
533     /**
534      * Sorting filter options
535      */
536
537     protected function sortByLastCommented(\Illuminate\Database\Eloquent\Builder $query, Entity $model)
538     {
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');
542
543         $query->join($commentQuery, $model->getTable() . '.id', '=', 'comments.entity_id')->orderBy('last_commented', 'desc');
544     }
545 }