]> BookStack Code Mirror - bookstack/blob - app/Entities/Entity.php
Add support Windows Authentication via SAML
[bookstack] / app / Entities / Entity.php
1 <?php namespace BookStack\Entities;
2
3 use BookStack\Actions\Activity;
4 use BookStack\Actions\Comment;
5 use BookStack\Actions\Tag;
6 use BookStack\Actions\View;
7 use BookStack\Auth\Permissions\EntityPermission;
8 use BookStack\Auth\Permissions\JointPermission;
9 use BookStack\Facades\Permissions;
10 use BookStack\Ownable;
11 use Carbon\Carbon;
12 use Illuminate\Database\Eloquent\Builder;
13 use Illuminate\Database\Eloquent\Collection;
14 use Illuminate\Database\Eloquent\Relations\MorphMany;
15
16 /**
17  * Class Entity
18  * The base class for book-like items such as pages, chapters & books.
19  * This is not a database model in itself but extended.
20  *
21  * @property int $id
22  * @property string $name
23  * @property string $slug
24  * @property Carbon $created_at
25  * @property Carbon $updated_at
26  * @property int $created_by
27  * @property int $updated_by
28  * @property boolean $restricted
29  * @property Collection $tags
30  * @method static Entity|Builder visible()
31  * @method static Entity|Builder hasPermission(string $permission)
32  * @method static Builder withLastView()
33  * @method static Builder withViewCount()
34  *
35  * @package BookStack\Entities
36  */
37 class Entity extends Ownable
38 {
39
40     /**
41      * @var string - Name of property where the main text content is found
42      */
43     public $textField = 'description';
44
45     /**
46      * @var float - Multiplier for search indexing.
47      */
48     public $searchFactor = 1.0;
49
50     /**
51      * Get the entities that are visible to the current user.
52      */
53     public function scopeVisible(Builder $query)
54     {
55         return $this->scopeHasPermission($query, 'view');
56     }
57
58     /**
59      * Scope the query to those entities that the current user has the given permission for.
60      */
61     public function scopeHasPermission(Builder $query, string $permission)
62     {
63         return Permissions::restrictEntityQuery($query, $permission);
64     }
65
66     /**
67      * Query scope to get the last view from the current user.
68      */
69     public function scopeWithLastView(Builder $query)
70     {
71         $viewedAtQuery = View::query()->select('updated_at')
72             ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
73             ->where('viewable_type', '=', $this->getMorphClass())
74             ->where('user_id', '=', user()->id)
75             ->take(1);
76
77         return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
78     }
79
80     /**
81      * Query scope to get the total view count of the entities.
82      */
83     public function scopeWithViewCount(Builder $query)
84     {
85         $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
86             ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
87             ->where('viewable_type', '=', $this->getMorphClass())->take(1);
88
89         $query->addSelect(['view_count' => $viewCountQuery]);
90     }
91
92     /**
93      * Compares this entity to another given entity.
94      * Matches by comparing class and id.
95      * @param $entity
96      * @return bool
97      */
98     public function matches($entity)
99     {
100         return [get_class($this), $this->id] === [get_class($entity), $entity->id];
101     }
102
103     /**
104      * Checks if an entity matches or contains another given entity.
105      * @param Entity $entity
106      * @return bool
107      */
108     public function matchesOrContains(Entity $entity)
109     {
110         $matches = [get_class($this), $this->id] === [get_class($entity), $entity->id];
111
112         if ($matches) {
113             return true;
114         }
115
116         if (($entity->isA('chapter') || $entity->isA('page')) && $this->isA('book')) {
117             return $entity->book_id === $this->id;
118         }
119
120         if ($entity->isA('page') && $this->isA('chapter')) {
121             return $entity->chapter_id === $this->id;
122         }
123
124         return false;
125     }
126
127     /**
128      * Gets the activity objects for this entity.
129      * @return MorphMany
130      */
131     public function activity()
132     {
133         return $this->morphMany(Activity::class, 'entity')
134             ->orderBy('created_at', 'desc');
135     }
136
137     /**
138      * Get View objects for this entity.
139      */
140     public function views()
141     {
142         return $this->morphMany(View::class, 'viewable');
143     }
144
145     /**
146      * Get the Tag models that have been user assigned to this entity.
147      * @return MorphMany
148      */
149     public function tags()
150     {
151         return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
152     }
153
154     /**
155      * Get the comments for an entity
156      * @param bool $orderByCreated
157      * @return MorphMany
158      */
159     public function comments($orderByCreated = true)
160     {
161         $query = $this->morphMany(Comment::class, 'entity');
162         return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
163     }
164
165     /**
166      * Get the related search terms.
167      * @return MorphMany
168      */
169     public function searchTerms()
170     {
171         return $this->morphMany(SearchTerm::class, 'entity');
172     }
173
174     /**
175      * Get this entities restrictions.
176      */
177     public function permissions()
178     {
179         return $this->morphMany(EntityPermission::class, 'restrictable');
180     }
181
182     /**
183      * Check if this entity has a specific restriction set against it.
184      * @param $role_id
185      * @param $action
186      * @return bool
187      */
188     public function hasRestriction($role_id, $action)
189     {
190         return $this->permissions()->where('role_id', '=', $role_id)
191             ->where('action', '=', $action)->count() > 0;
192     }
193
194     /**
195      * Get the entity jointPermissions this is connected to.
196      * @return MorphMany
197      */
198     public function jointPermissions()
199     {
200         return $this->morphMany(JointPermission::class, 'entity');
201     }
202
203     /**
204      * Allows checking of the exact class, Used to check entity type.
205      * Cleaner method for is_a.
206      * @param $type
207      * @return bool
208      */
209     public static function isA($type)
210     {
211         return static::getType() === strtolower($type);
212     }
213
214     /**
215      * Get entity type.
216      * @return mixed
217      */
218     public static function getType()
219     {
220         return strtolower(static::getClassName());
221     }
222
223     /**
224      * Get an instance of an entity of the given type.
225      * @param $type
226      * @return Entity
227      */
228     public static function getEntityInstance($type)
229     {
230         $types = ['Page', 'Book', 'Chapter', 'Bookshelf'];
231         $className = str_replace([' ', '-', '_'], '', ucwords($type));
232         if (!in_array($className, $types)) {
233             return null;
234         }
235
236         return app('BookStack\\Entities\\' . $className);
237     }
238
239     /**
240      * Gets a limited-length version of the entities name.
241      * @param int $length
242      * @return string
243      */
244     public function getShortName($length = 25)
245     {
246         if (mb_strlen($this->name) <= $length) {
247             return $this->name;
248         }
249         return mb_substr($this->name, 0, $length - 3) . '...';
250     }
251
252     /**
253      * Get the body text of this entity.
254      * @return mixed
255      */
256     public function getText()
257     {
258         return $this->{$this->textField};
259     }
260
261     /**
262      * Get an excerpt of this entity's descriptive content to the specified length.
263      * @param int $length
264      * @return mixed
265      */
266     public function getExcerpt(int $length = 100)
267     {
268         $text = $this->getText();
269         if (mb_strlen($text) > $length) {
270             $text = mb_substr($text, 0, $length-3) . '...';
271         }
272         return trim($text);
273     }
274
275     /**
276      * Get the url of this entity
277      * @param $path
278      * @return string
279      */
280     public function getUrl($path = '/')
281     {
282         return $path;
283     }
284
285     /**
286      * Rebuild the permissions for this entity.
287      */
288     public function rebuildPermissions()
289     {
290         /** @noinspection PhpUnhandledExceptionInspection */
291         Permissions::buildJointPermissionsForEntity($this);
292     }
293
294     /**
295      * Index the current entity for search
296      */
297     public function indexForSearch()
298     {
299         $searchService = app()->make(SearchService::class);
300         $searchService->indexEntity($this);
301     }
302
303     /**
304      * Generate and set a new URL slug for this model.
305      */
306     public function refreshSlug(): string
307     {
308         $generator = new SlugGenerator($this);
309         $this->slug = $generator->generate();
310         return $this->slug;
311     }
312 }