]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/Entity.php
Adjusted/improved some color setting wording
[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\SlugGenerator;
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\References\Reference;
22 use BookStack\Search\SearchIndex;
23 use BookStack\Search\SearchTerm;
24 use BookStack\Traits\HasCreatorAndUpdater;
25 use BookStack\Traits\HasOwner;
26 use Carbon\Carbon;
27 use Illuminate\Database\Eloquent\Builder;
28 use Illuminate\Database\Eloquent\Collection;
29 use Illuminate\Database\Eloquent\Relations\MorphMany;
30 use Illuminate\Database\Eloquent\SoftDeletes;
31
32 /**
33  * Class Entity
34  * The base class for book-like items such as pages, chapters & books.
35  * This is not a database model in itself but extended.
36  *
37  * @property int        $id
38  * @property string     $name
39  * @property string     $slug
40  * @property Carbon     $created_at
41  * @property Carbon     $updated_at
42  * @property Carbon     $deleted_at
43  * @property int        $created_by
44  * @property int        $updated_by
45  * @property Collection $tags
46  *
47  * @method static Entity|Builder visible()
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 app()->make(PermissionApplicator::class)->restrictEntityQuery($query);
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(self $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(self $entity): bool
114     {
115         if ($this->matches($entity)) {
116             return true;
117         }
118
119         if (($entity instanceof BookChild) && $this instanceof Book) {
120             return $entity->book_id === $this->id;
121         }
122
123         if ($entity instanceof Page && $this instanceof 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
162         return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
163     }
164
165     /**
166      * Get the related search terms.
167      */
168     public function searchTerms(): MorphMany
169     {
170         return $this->morphMany(SearchTerm::class, 'entity');
171     }
172
173     /**
174      * Get this entities restrictions.
175      */
176     public function permissions(): MorphMany
177     {
178         return $this->morphMany(EntityPermission::class, 'entity');
179     }
180
181     /**
182      * Check if this entity has a specific restriction set against it.
183      */
184     public function hasPermissions(): bool
185     {
186         return $this->permissions()->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      * Get the references pointing from this entity to other items.
207      */
208     public function referencesFrom(): MorphMany
209     {
210         return $this->morphMany(Reference::class, 'from');
211     }
212
213     /**
214      * Get the references pointing to this entity from other items.
215      */
216     public function referencesTo(): MorphMany
217     {
218         return $this->morphMany(Reference::class, 'to');
219     }
220
221     /**
222      * Check if this instance or class is a certain type of entity.
223      * Examples of $type are 'page', 'book', 'chapter'.
224      *
225      * @deprecated Use instanceof instead.
226      */
227     public static function isA(string $type): bool
228     {
229         return static::getType() === strtolower($type);
230     }
231
232     /**
233      * Get the entity type as a simple lowercase word.
234      */
235     public static function getType(): string
236     {
237         $className = array_slice(explode('\\', static::class), -1, 1)[0];
238
239         return strtolower($className);
240     }
241
242     /**
243      * Gets a limited-length version of the entities name.
244      */
245     public function getShortName(int $length = 25): string
246     {
247         if (mb_strlen($this->name) <= $length) {
248             return $this->name;
249         }
250
251         return mb_substr($this->name, 0, $length - 3) . '...';
252     }
253
254     /**
255      * Get an excerpt of this entity's descriptive content to the specified length.
256      */
257     public function getExcerpt(int $length = 100): string
258     {
259         $text = $this->{$this->textField} ?? '';
260
261         if (mb_strlen($text) > $length) {
262             $text = mb_substr($text, 0, $length - 3) . '...';
263         }
264
265         return trim($text);
266     }
267
268     /**
269      * Get the url of this entity.
270      */
271     abstract public function getUrl(string $path = '/'): string;
272
273     /**
274      * Get the parent entity if existing.
275      * This is the "static" parent and does not include dynamic
276      * relations such as shelves to books.
277      */
278     public function getParent(): ?self
279     {
280         if ($this instanceof Page) {
281             return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
282         }
283         if ($this instanceof Chapter) {
284             return $this->book()->withTrashed()->first();
285         }
286
287         return null;
288     }
289
290     /**
291      * Rebuild the permissions for this entity.
292      */
293     public function rebuildPermissions()
294     {
295         app()->make(JointPermissionBuilder::class)->rebuildForEntity(clone $this);
296     }
297
298     /**
299      * Index the current entity for search.
300      */
301     public function indexForSearch()
302     {
303         app()->make(SearchIndex::class)->indexEntity(clone $this);
304     }
305
306     /**
307      * {@inheritdoc}
308      */
309     public function refreshSlug(): string
310     {
311         $this->slug = app()->make(SlugGenerator::class)->generate($this);
312
313         return $this->slug;
314     }
315
316     /**
317      * {@inheritdoc}
318      */
319     public function favourites(): MorphMany
320     {
321         return $this->morphMany(Favourite::class, 'favouritable');
322     }
323
324     /**
325      * Check if the entity is a favourite of the current user.
326      */
327     public function isFavourite(): bool
328     {
329         return $this->favourites()
330             ->where('user_id', '=', user()->id)
331             ->exists();
332     }
333
334     /**
335      * {@inheritdoc}
336      */
337     public function logDescriptor(): string
338     {
339         return "({$this->id}) {$this->name}";
340     }
341 }