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