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