]> BookStack Code Mirror - bookstack/blob - app/Services/SearchService.php
ec4889e50b1aee47345ad51cd94274c93ca1b320
[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      * Search all entities in the system.
55      * @param string $searchString
56      * @param string $entityType
57      * @param int $page
58      * @param int $count
59      * @return array[int, Collection];
60      */
61     public function searchEntities($searchString, $entityType = 'all', $page = 1, $count = 20)
62     {
63         $terms = $this->parseSearchString($searchString);
64         $entityTypes = array_keys($this->entities);
65         $entityTypesToSearch = $entityTypes;
66         $results = collect();
67
68         if ($entityType !== 'all') {
69             $entityTypesToSearch = $entityType;
70         } else if (isset($terms['filters']['type'])) {
71             $entityTypesToSearch = explode('|', $terms['filters']['type']);
72         }
73
74         $total = 0;
75
76         foreach ($entityTypesToSearch as $entityType) {
77             if (!in_array($entityType, $entityTypes)) continue;
78             $search = $this->searchEntityTable($terms, $entityType, $page, $count);
79             $total += $this->searchEntityTable($terms, $entityType, $page, $count, true);
80             $results = $results->merge($search);
81         }
82
83         return [
84             'total' => $total,
85             'count' => count($results),
86             'results' => $results->sortByDesc('score')
87         ];
88     }
89
90
91     /**
92      * Search a book for entities
93      * @param integer $bookId
94      * @param string $searchString
95      * @return Collection
96      */
97     public function searchBook($bookId, $searchString)
98     {
99         $terms = $this->parseSearchString($searchString);
100         $results = collect();
101         $pages = $this->buildEntitySearchQuery($terms, 'page')->where('book_id', '=', $bookId)->take(20)->get();
102         $chapters = $this->buildEntitySearchQuery($terms, 'chapter')->where('book_id', '=', $bookId)->take(20)->get();
103         return $results->merge($pages)->merge($chapters)->sortByDesc('score')->take(20);
104     }
105
106     /**
107      * Search a book for entities
108      * @param integer $chapterId
109      * @param string $searchString
110      * @return Collection
111      */
112     public function searchChapter($chapterId, $searchString)
113     {
114         $terms = $this->parseSearchString($searchString);
115         $pages = $this->buildEntitySearchQuery($terms, 'page')->where('chapter_id', '=', $chapterId)->take(20)->get();
116         return $pages->sortByDesc('score');
117     }
118
119     /**
120      * Search across a particular entity type.
121      * @param array $terms
122      * @param string $entityType
123      * @param int $page
124      * @param int $count
125      * @param bool $getCount Return the total count of the search
126      * @return \Illuminate\Database\Eloquent\Collection|int|static[]
127      */
128     public function searchEntityTable($terms, $entityType = 'page', $page = 1, $count = 20, $getCount = false)
129     {
130         $query = $this->buildEntitySearchQuery($terms, $entityType);
131         if ($getCount) return $query->count();
132
133         $query = $query->skip(($page-1) * $count)->take($count);
134         return $query->get();
135     }
136
137     /**
138      * Create a search query for an entity
139      * @param array $terms
140      * @param string $entityType
141      * @return \Illuminate\Database\Eloquent\Builder
142      */
143     protected function buildEntitySearchQuery($terms, $entityType = 'page')
144     {
145         $entity = $this->getEntity($entityType);
146         $entitySelect = $entity->newQuery();
147
148         // Handle normal search terms
149         if (count($terms['search']) > 0) {
150             $subQuery = $this->db->table('search_terms')->select('entity_id', 'entity_type', \DB::raw('SUM(score) as score'));
151             $subQuery->where(function(Builder $query) use ($terms) {
152                 foreach ($terms['search'] as $inputTerm) {
153                     $query->orWhere('term', 'like', $inputTerm .'%');
154                 }
155             })->groupBy('entity_type', 'entity_id');
156             $entitySelect->join(\DB::raw('(' . $subQuery->toSql() . ') as s'), function(JoinClause $join) {
157                 $join->on('id', '=', 'entity_id');
158             })->selectRaw($entity->getTable().'.*, s.score')->orderBy('score', 'desc');
159             $entitySelect->mergeBindings($subQuery);
160         }
161
162         // Handle exact term matching
163         if (count($terms['exact']) > 0) {
164             $entitySelect->where(function(\Illuminate\Database\Eloquent\Builder $query) use ($terms, $entity) {
165                 foreach ($terms['exact'] as $inputTerm) {
166                     $query->where(function (\Illuminate\Database\Eloquent\Builder $query) use ($inputTerm, $entity) {
167                         $query->where('name', 'like', '%'.$inputTerm .'%')
168                             ->orWhere($entity->textField, 'like', '%'.$inputTerm .'%');
169                     });
170                 }
171             });
172         }
173
174         // Handle tag searches
175         foreach ($terms['tags'] as $inputTerm) {
176             $this->applyTagSearch($entitySelect, $inputTerm);
177         }
178
179         // Handle filters
180         foreach ($terms['filters'] as $filterTerm => $filterValue) {
181             $functionName = camel_case('filter_' . $filterTerm);
182             if (method_exists($this, $functionName)) $this->$functionName($entitySelect, $entity, $filterValue);
183         }
184
185         return $this->permissionService->enforceEntityRestrictions($entityType, $entitySelect, 'view');
186     }
187
188
189     /**
190      * Parse a search string into components.
191      * @param $searchString
192      * @return array
193      */
194     protected function parseSearchString($searchString)
195     {
196         $terms = [
197             'search' => [],
198             'exact' => [],
199             'tags' => [],
200             'filters' => []
201         ];
202
203         $patterns = [
204             'exact' => '/"(.*?)"/',
205             'tags' => '/\[(.*?)\]/',
206             'filters' => '/\{(.*?)\}/'
207         ];
208
209         // Parse special terms
210         foreach ($patterns as $termType => $pattern) {
211             $matches = [];
212             preg_match_all($pattern, $searchString, $matches);
213             if (count($matches) > 0) {
214                 $terms[$termType] = $matches[1];
215                 $searchString = preg_replace($pattern, '', $searchString);
216             }
217         }
218
219         // Parse standard terms
220         foreach (explode(' ', trim($searchString)) as $searchTerm) {
221             if ($searchTerm !== '') $terms['search'][] = $searchTerm;
222         }
223
224         // Split filter values out
225         $splitFilters = [];
226         foreach ($terms['filters'] as $filter) {
227             $explodedFilter = explode(':', $filter, 2);
228             $splitFilters[$explodedFilter[0]] = (count($explodedFilter) > 1) ? $explodedFilter[1] : '';
229         }
230         $terms['filters'] = $splitFilters;
231
232         return $terms;
233     }
234
235     /**
236      * Get the available query operators as a regex escaped list.
237      * @return mixed
238      */
239     protected function getRegexEscapedOperators()
240     {
241         $escapedOperators = [];
242         foreach ($this->queryOperators as $operator) {
243             $escapedOperators[] = preg_quote($operator);
244         }
245         return join('|', $escapedOperators);
246     }
247
248     /**
249      * Apply a tag search term onto a entity query.
250      * @param \Illuminate\Database\Eloquent\Builder $query
251      * @param string $tagTerm
252      * @return mixed
253      */
254     protected function applyTagSearch(\Illuminate\Database\Eloquent\Builder $query, $tagTerm) {
255         preg_match("/^(.*?)((".$this->getRegexEscapedOperators().")(.*?))?$/", $tagTerm, $tagSplit);
256         $query->whereHas('tags', function(\Illuminate\Database\Eloquent\Builder $query) use ($tagSplit) {
257             $tagName = $tagSplit[1];
258             $tagOperator = count($tagSplit) > 2 ? $tagSplit[3] : '';
259             $tagValue = count($tagSplit) > 3 ? $tagSplit[4] : '';
260             $validOperator = in_array($tagOperator, $this->queryOperators);
261             if (!empty($tagOperator) && !empty($tagValue) && $validOperator) {
262                 if (!empty($tagName)) $query->where('name', '=', $tagName);
263                 if (is_numeric($tagValue) && $tagOperator !== 'like') {
264                     // We have to do a raw sql query for this since otherwise PDO will quote the value and MySQL will
265                     // search the value as a string which prevents being able to do number-based operations
266                     // on the tag values. We ensure it has a numeric value and then cast it just to be sure.
267                     $tagValue = (float) trim($query->getConnection()->getPdo()->quote($tagValue), "'");
268                     $query->whereRaw("value ${tagOperator} ${tagValue}");
269                 } else {
270                     $query->where('value', $tagOperator, $tagValue);
271                 }
272             } else {
273                 $query->where('name', '=', $tagName);
274             }
275         });
276         return $query;
277     }
278
279     /**
280      * Get an entity instance via type.
281      * @param $type
282      * @return Entity
283      */
284     protected function getEntity($type)
285     {
286         return $this->entities[strtolower($type)];
287     }
288
289     /**
290      * Index the given entity.
291      * @param Entity $entity
292      */
293     public function indexEntity(Entity $entity)
294     {
295         $this->deleteEntityTerms($entity);
296         $nameTerms = $this->generateTermArrayFromText($entity->name, 5);
297         $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1);
298         $terms = array_merge($nameTerms, $bodyTerms);
299         foreach ($terms as $index => $term) {
300             $terms[$index]['entity_type'] = $entity->getMorphClass();
301             $terms[$index]['entity_id'] = $entity->id;
302         }
303         $this->searchTerm->newQuery()->insert($terms);
304     }
305
306     /**
307      * Index multiple Entities at once
308      * @param Entity[] $entities
309      */
310     protected function indexEntities($entities) {
311         $terms = [];
312         foreach ($entities as $entity) {
313             $nameTerms = $this->generateTermArrayFromText($entity->name, 5);
314             $bodyTerms = $this->generateTermArrayFromText($entity->getText(), 1);
315             foreach (array_merge($nameTerms, $bodyTerms) as $term) {
316                 $term['entity_id'] = $entity->id;
317                 $term['entity_type'] = $entity->getMorphClass();
318                 $terms[] = $term;
319             }
320         }
321
322         $chunkedTerms = array_chunk($terms, 500);
323         foreach ($chunkedTerms as $termChunk) {
324             $this->searchTerm->newQuery()->insert($termChunk);
325         }
326     }
327
328     /**
329      * Delete and re-index the terms for all entities in the system.
330      */
331     public function indexAllEntities()
332     {
333         $this->searchTerm->truncate();
334
335         // Chunk through all books
336         $this->book->chunk(1000, function ($books) {
337             $this->indexEntities($books);
338         });
339
340         // Chunk through all chapters
341         $this->chapter->chunk(1000, function ($chapters) {
342             $this->indexEntities($chapters);
343         });
344
345         // Chunk through all pages
346         $this->page->chunk(1000, function ($pages) {
347             $this->indexEntities($pages);
348         });
349     }
350
351     /**
352      * Delete related Entity search terms.
353      * @param Entity $entity
354      */
355     public function deleteEntityTerms(Entity $entity)
356     {
357         $entity->searchTerms()->delete();
358     }
359
360     /**
361      * Create a scored term array from the given text.
362      * @param $text
363      * @param float|int $scoreAdjustment
364      * @return array
365      */
366     protected function generateTermArrayFromText($text, $scoreAdjustment = 1)
367     {
368         $tokenMap = []; // {TextToken => OccurrenceCount}
369         $splitText = explode(' ', $text);
370         foreach ($splitText as $token) {
371             if ($token === '') continue;
372             if (!isset($tokenMap[$token])) $tokenMap[$token] = 0;
373             $tokenMap[$token]++;
374         }
375
376         $terms = [];
377         foreach ($tokenMap as $token => $count) {
378             $terms[] = [
379                 'term' => $token,
380                 'score' => $count * $scoreAdjustment
381             ];
382         }
383         return $terms;
384     }
385
386
387
388
389     /**
390      * Custom entity search filters
391      */
392
393     protected function filterUpdatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
394     {
395         try { $date = date_create($input);
396         } catch (\Exception $e) {return;}
397         $query->where('updated_at', '>=', $date);
398     }
399
400     protected function filterUpdatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
401     {
402         try { $date = date_create($input);
403         } catch (\Exception $e) {return;}
404         $query->where('updated_at', '<', $date);
405     }
406
407     protected function filterCreatedAfter(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
408     {
409         try { $date = date_create($input);
410         } catch (\Exception $e) {return;}
411         $query->where('created_at', '>=', $date);
412     }
413
414     protected function filterCreatedBefore(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
415     {
416         try { $date = date_create($input);
417         } catch (\Exception $e) {return;}
418         $query->where('created_at', '<', $date);
419     }
420
421     protected function filterCreatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
422     {
423         if (!is_numeric($input) && $input !== 'me') return;
424         if ($input === 'me') $input = user()->id;
425         $query->where('created_by', '=', $input);
426     }
427
428     protected function filterUpdatedBy(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
429     {
430         if (!is_numeric($input) && $input !== 'me') return;
431         if ($input === 'me') $input = user()->id;
432         $query->where('updated_by', '=', $input);
433     }
434
435     protected function filterInName(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
436     {
437         $query->where('name', 'like', '%' .$input. '%');
438     }
439
440     protected function filterInTitle(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input) {$this->filterInName($query, $model, $input);}
441
442     protected function filterInBody(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
443     {
444         $query->where($model->textField, 'like', '%' .$input. '%');
445     }
446
447     protected function filterIsRestricted(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
448     {
449         $query->where('restricted', '=', true);
450     }
451
452     protected function filterViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
453     {
454         $query->whereHas('views', function($query) {
455             $query->where('user_id', '=', user()->id);
456         });
457     }
458
459     protected function filterNotViewedByMe(\Illuminate\Database\Eloquent\Builder $query, Entity $model, $input)
460     {
461         $query->whereDoesntHave('views', function($query) {
462             $query->where('user_id', '=', user()->id);
463         });
464     }
465
466 }