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