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