]> BookStack Code Mirror - bookstack/blob - app/Entity.php
52b214eb3ab80ea9296af4c968dc207a8ae3cc1b
[bookstack] / app / Entity.php
1 <?php namespace BookStack;
2
3
4 class Entity extends Ownable
5 {
6
7     public $textField = 'description';
8
9     /**
10      * Compares this entity to another given entity.
11      * Matches by comparing class and id.
12      * @param $entity
13      * @return bool
14      */
15     public function matches($entity)
16     {
17         return [get_class($this), $this->id] === [get_class($entity), $entity->id];
18     }
19
20     /**
21      * Checks if an entity matches or contains another given entity.
22      * @param Entity $entity
23      * @return bool
24      */
25     public function matchesOrContains(Entity $entity)
26     {
27         $matches = [get_class($this), $this->id] === [get_class($entity), $entity->id];
28
29         if ($matches) return true;
30
31         if (($entity->isA('chapter') || $entity->isA('page')) && $this->isA('book')) {
32             return $entity->book_id === $this->id;
33         }
34
35         if ($entity->isA('page') && $this->isA('chapter')) {
36             return $entity->chapter_id === $this->id;
37         }
38
39         return false;
40     }
41
42     /**
43      * Gets the activity objects for this entity.
44      * @return \Illuminate\Database\Eloquent\Relations\MorphMany
45      */
46     public function activity()
47     {
48         return $this->morphMany(Activity::class, 'entity')->orderBy('created_at', 'desc');
49     }
50
51     /**
52      * Get View objects for this entity.
53      */
54     public function views()
55     {
56         return $this->morphMany(View::class, 'viewable');
57     }
58
59     /**
60      * Get the Tag models that have been user assigned to this entity.
61      * @return \Illuminate\Database\Eloquent\Relations\MorphMany
62      */
63     public function tags()
64     {
65         return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
66     }
67
68     /**
69      * Get the related search terms.
70      * @return \Illuminate\Database\Eloquent\Relations\MorphMany
71      */
72     public function searchTerms()
73     {
74         return $this->morphMany(SearchTerm::class, 'entity');
75     }
76
77     /**
78      * Get this entities restrictions.
79      */
80     public function permissions()
81     {
82         return $this->morphMany(EntityPermission::class, 'restrictable');
83     }
84
85     /**
86      * Check if this entity has a specific restriction set against it.
87      * @param $role_id
88      * @param $action
89      * @return bool
90      */
91     public function hasRestriction($role_id, $action)
92     {
93         return $this->permissions()->where('role_id', '=', $role_id)
94             ->where('action', '=', $action)->count() > 0;
95     }
96
97     /**
98      * Check if this entity has live (active) restrictions in place.
99      * @param $role_id
100      * @param $action
101      * @return bool
102      */
103     public function hasActiveRestriction($role_id, $action)
104     {
105         return $this->getRawAttribute('restricted') && $this->hasRestriction($role_id, $action);
106     }
107
108     /**
109      * Get the entity jointPermissions this is connected to.
110      * @return \Illuminate\Database\Eloquent\Relations\MorphMany
111      */
112     public function jointPermissions()
113     {
114         return $this->morphMany(JointPermission::class, 'entity');
115     }
116
117     /**
118      * Allows checking of the exact class, Used to check entity type.
119      * Cleaner method for is_a.
120      * @param $type
121      * @return bool
122      */
123     public static function isA($type)
124     {
125         return static::getType() === strtolower($type);
126     }
127
128     /**
129      * Get entity type.
130      * @return mixed
131      */
132     public static function getType()
133     {
134         return strtolower(static::getClassName());
135     }
136
137     /**
138      * Get an instance of an entity of the given type.
139      * @param $type
140      * @return Entity
141      */
142     public static function getEntityInstance($type)
143     {
144         $types = ['Page', 'Book', 'Chapter'];
145         $className = str_replace([' ', '-', '_'], '', ucwords($type));
146         if (!in_array($className, $types)) {
147             return null;
148         }
149
150         return app('BookStack\\' . $className);
151     }
152
153     /**
154      * Gets a limited-length version of the entities name.
155      * @param int $length
156      * @return string
157      */
158     public function getShortName($length = 25)
159     {
160         if (strlen($this->name) <= $length) return $this->name;
161         return substr($this->name, 0, $length - 3) . '...';
162     }
163
164     /**
165      * Get the body text of this entity.
166      * @return mixed
167      */
168     public function getText()
169     {
170         return $this->{$this->textField};
171     }
172
173     /**
174      * Return a generalised, common raw query that can be 'unioned' across entities.
175      * @return string
176      */
177     public function entityRawQuery(){return '';}
178
179     /**
180      * Perform a full-text search on this entity.
181      * @param string[] $terms
182      * @param string[] array $wheres
183      * TODO - REMOVE
184      * @return mixed
185      */
186     public function fullTextSearchQuery($terms, $wheres = [])
187     {
188         $exactTerms = [];
189         $fuzzyTerms = [];
190         $search = static::newQuery();
191
192         foreach ($terms as $key => $term) {
193             $term = htmlentities($term, ENT_QUOTES);
194             $term = preg_replace('/[+\-><\(\)~*\"@]+/', ' ', $term);
195             if (preg_match('/&quot;.*?&quot;/', $term) || is_numeric($term)) {
196                 $term = str_replace('&quot;', '', $term);
197                 $exactTerms[] = '%' . $term . '%';
198             } else {
199                 $term = '' . $term . '*';
200                 if ($term !== '*') $fuzzyTerms[] = $term;
201             }
202         }
203
204         $isFuzzy = count($exactTerms) === 0 && count($fuzzyTerms) > 0;
205         $fieldsToSearch = ['name', $this->textField];
206
207         // Perform fulltext search if relevant terms exist.
208         if ($isFuzzy) {
209             $termString = implode(' ', $fuzzyTerms);
210
211             $search = $search->selectRaw('*, MATCH(name) AGAINST(? IN BOOLEAN MODE) AS title_relevance', [$termString]);
212             $search = $search->whereRaw('MATCH(' . implode(',', $fieldsToSearch ). ') AGAINST(? IN BOOLEAN MODE)', [$termString]);
213         }
214
215         // Ensure at least one exact term matches if in search
216         if (count($exactTerms) > 0) {
217             $search = $search->where(function ($query) use ($exactTerms, $fieldsToSearch) {
218                 foreach ($exactTerms as $exactTerm) {
219                     foreach ($fieldsToSearch as $field) {
220                         $query->orWhere($field, 'like', $exactTerm);
221                     }
222                 }
223             });
224         }
225
226         $orderBy = $isFuzzy ? 'title_relevance' : 'updated_at';
227
228         // Add additional where terms
229         foreach ($wheres as $whereTerm) {
230             $search->where($whereTerm[0], $whereTerm[1], $whereTerm[2]);
231         }
232
233         // Load in relations
234         if ($this->isA('page')) {
235             $search = $search->with('book', 'chapter', 'createdBy', 'updatedBy');
236         } else if ($this->isA('chapter')) {
237             $search = $search->with('book');
238         }
239
240         return $search->orderBy($orderBy, 'desc');
241     }
242
243 }