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