]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/Entity.php
Improved shelf book management interface
[bookstack] / app / Entities / Models / Entity.php
1 <?php
2
3 namespace BookStack\Entities\Models;
4
5 use BookStack\Actions\Activity;
6 use BookStack\Actions\Comment;
7 use BookStack\Actions\Favourite;
8 use BookStack\Actions\Tag;
9 use BookStack\Actions\View;
10 use BookStack\Auth\Permissions\EntityPermission;
11 use BookStack\Auth\Permissions\JointPermission;
12 use BookStack\Auth\Permissions\JointPermissionBuilder;
13 use BookStack\Auth\Permissions\PermissionApplicator;
14 use BookStack\Entities\Tools\SearchIndex;
15 use BookStack\Entities\Tools\SlugGenerator;
16 use BookStack\Interfaces\Deletable;
17 use BookStack\Interfaces\Favouritable;
18 use BookStack\Interfaces\Loggable;
19 use BookStack\Interfaces\Sluggable;
20 use BookStack\Interfaces\Viewable;
21 use BookStack\Model;
22 use BookStack\Traits\HasCreatorAndUpdater;
23 use BookStack\Traits\HasOwner;
24 use Carbon\Carbon;
25 use Illuminate\Database\Eloquent\Builder;
26 use Illuminate\Database\Eloquent\Collection;
27 use Illuminate\Database\Eloquent\Relations\MorphMany;
28 use Illuminate\Database\Eloquent\SoftDeletes;
29
30 /**
31  * Class Entity
32  * The base class for book-like items such as pages, chapters & books.
33  * This is not a database model in itself but extended.
34  *
35  * @property int        $id
36  * @property string     $name
37  * @property string     $slug
38  * @property Carbon     $created_at
39  * @property Carbon     $updated_at
40  * @property Carbon     $deleted_at
41  * @property int        $created_by
42  * @property int        $updated_by
43  * @property bool       $restricted
44  * @property Collection $tags
45  *
46  * @method static Entity|Builder visible()
47  * @method static Builder withLastView()
48  * @method static Builder withViewCount()
49  */
50 abstract class Entity extends Model implements Sluggable, Favouritable, Viewable, Deletable, Loggable
51 {
52     use SoftDeletes;
53     use HasCreatorAndUpdater;
54     use HasOwner;
55
56     /**
57      * @var string - Name of property where the main text content is found
58      */
59     public $textField = 'description';
60
61     /**
62      * @var float - Multiplier for search indexing.
63      */
64     public $searchFactor = 1.0;
65
66     /**
67      * Get the entities that are visible to the current user.
68      */
69     public function scopeVisible(Builder $query): Builder
70     {
71         return app()->make(PermissionApplicator::class)->restrictEntityQuery($query);
72     }
73
74     /**
75      * Query scope to get the last view from the current user.
76      */
77     public function scopeWithLastView(Builder $query)
78     {
79         $viewedAtQuery = View::query()->select('updated_at')
80             ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
81             ->where('viewable_type', '=', $this->getMorphClass())
82             ->where('user_id', '=', user()->id)
83             ->take(1);
84
85         return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
86     }
87
88     /**
89      * Query scope to get the total view count of the entities.
90      */
91     public function scopeWithViewCount(Builder $query)
92     {
93         $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
94             ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
95             ->where('viewable_type', '=', $this->getMorphClass())->take(1);
96
97         $query->addSelect(['view_count' => $viewCountQuery]);
98     }
99
100     /**
101      * Compares this entity to another given entity.
102      * Matches by comparing class and id.
103      */
104     public function matches(self $entity): bool
105     {
106         return [get_class($this), $this->id] === [get_class($entity), $entity->id];
107     }
108
109     /**
110      * Checks if the current entity matches or contains the given.
111      */
112     public function matchesOrContains(self $entity): bool
113     {
114         if ($this->matches($entity)) {
115             return true;
116         }
117
118         if (($entity instanceof BookChild) && $this instanceof Book) {
119             return $entity->book_id === $this->id;
120         }
121
122         if ($entity instanceof Page && $this instanceof 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      */
132     public function activity(): MorphMany
133     {
134         return $this->morphMany(Activity::class, 'entity')
135             ->orderBy('created_at', 'desc');
136     }
137
138     /**
139      * Get View objects for this entity.
140      */
141     public function views(): MorphMany
142     {
143         return $this->morphMany(View::class, 'viewable');
144     }
145
146     /**
147      * Get the Tag models that have been user assigned to this entity.
148      */
149     public function tags(): MorphMany
150     {
151         return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
152     }
153
154     /**
155      * Get the comments for an entity.
156      */
157     public function comments(bool $orderByCreated = true): MorphMany
158     {
159         $query = $this->morphMany(Comment::class, 'entity');
160
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      * @deprecated Use instanceof instead.
210      */
211     public static function isA(string $type): bool
212     {
213         return static::getType() === strtolower($type);
214     }
215
216     /**
217      * Get the entity type as a simple lowercase word.
218      */
219     public static function getType(): string
220     {
221         $className = array_slice(explode('\\', static::class), -1, 1)[0];
222
223         return strtolower($className);
224     }
225
226     /**
227      * Gets a limited-length version of the entities name.
228      */
229     public function getShortName(int $length = 25): string
230     {
231         if (mb_strlen($this->name) <= $length) {
232             return $this->name;
233         }
234
235         return mb_substr($this->name, 0, $length - 3) . '...';
236     }
237
238     /**
239      * Get an excerpt of this entity's descriptive content to the specified length.
240      */
241     public function getExcerpt(int $length = 100): string
242     {
243         $text = $this->{$this->textField} ?? '';
244
245         if (mb_strlen($text) > $length) {
246             $text = mb_substr($text, 0, $length - 3) . '...';
247         }
248
249         return trim($text);
250     }
251
252     /**
253      * Get the url of this entity.
254      */
255     abstract public function getUrl(string $path = '/'): string;
256
257     /**
258      * Get the parent entity if existing.
259      * This is the "static" parent and does not include dynamic
260      * relations such as shelves to books.
261      */
262     public function getParent(): ?self
263     {
264         if ($this instanceof Page) {
265             return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
266         }
267         if ($this instanceof Chapter) {
268             return $this->book()->withTrashed()->first();
269         }
270
271         return null;
272     }
273
274     /**
275      * Rebuild the permissions for this entity.
276      */
277     public function rebuildPermissions()
278     {
279         app()->make(JointPermissionBuilder::class)->rebuildForEntity(clone $this);
280     }
281
282     /**
283      * Index the current entity for search.
284      */
285     public function indexForSearch()
286     {
287         app()->make(SearchIndex::class)->indexEntity(clone $this);
288     }
289
290     /**
291      * {@inheritdoc}
292      */
293     public function refreshSlug(): string
294     {
295         $this->slug = app()->make(SlugGenerator::class)->generate($this);
296
297         return $this->slug;
298     }
299
300     /**
301      * {@inheritdoc}
302      */
303     public function favourites(): MorphMany
304     {
305         return $this->morphMany(Favourite::class, 'favouritable');
306     }
307
308     /**
309      * Check if the entity is a favourite of the current user.
310      */
311     public function isFavourite(): bool
312     {
313         return $this->favourites()
314             ->where('user_id', '=', user()->id)
315             ->exists();
316     }
317
318     /**
319      * {@inheritdoc}
320      */
321     public function logDescriptor(): string
322     {
323         return "({$this->id}) {$this->name}";
324     }
325 }