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