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