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