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