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