]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/Entity.php
Comments: Added text for new activity types
[bookstack] / app / Entities / Models / Entity.php
1 <?php
2
3 namespace BookStack\Entities\Models;
4
5 use BookStack\Activity\Models\Activity;
6 use BookStack\Activity\Models\Comment;
7 use BookStack\Activity\Models\Favouritable;
8 use BookStack\Activity\Models\Favourite;
9 use BookStack\Activity\Models\Loggable;
10 use BookStack\Activity\Models\Tag;
11 use BookStack\Activity\Models\View;
12 use BookStack\Activity\Models\Viewable;
13 use BookStack\App\Model;
14 use BookStack\App\Sluggable;
15 use BookStack\Entities\Tools\SlugGenerator;
16 use BookStack\Permissions\JointPermissionBuilder;
17 use BookStack\Permissions\Models\EntityPermission;
18 use BookStack\Permissions\Models\JointPermission;
19 use BookStack\Permissions\PermissionApplicator;
20 use BookStack\References\Reference;
21 use BookStack\Search\SearchIndex;
22 use BookStack\Search\SearchTerm;
23 use BookStack\Users\Models\HasCreatorAndUpdater;
24 use BookStack\Users\Models\HasOwner;
25 use Carbon\Carbon;
26 use Illuminate\Database\Eloquent\Builder;
27 use Illuminate\Database\Eloquent\Collection;
28 use Illuminate\Database\Eloquent\Relations\MorphMany;
29 use Illuminate\Database\Eloquent\SoftDeletes;
30
31 /**
32  * Class Entity
33  * The base class for book-like items such as pages, chapters & books.
34  * This is not a database model in itself but extended.
35  *
36  * @property int        $id
37  * @property string     $name
38  * @property string     $slug
39  * @property Carbon     $created_at
40  * @property Carbon     $updated_at
41  * @property Carbon     $deleted_at
42  * @property int        $created_by
43  * @property int        $updated_by
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, 'entity');
178     }
179
180     /**
181      * Check if this entity has a specific restriction set against it.
182      */
183     public function hasPermissions(): bool
184     {
185         return $this->permissions()->count() > 0;
186     }
187
188     /**
189      * Get the entity jointPermissions this is connected to.
190      */
191     public function jointPermissions(): MorphMany
192     {
193         return $this->morphMany(JointPermission::class, 'entity');
194     }
195
196     /**
197      * Get the related delete records for this entity.
198      */
199     public function deletions(): MorphMany
200     {
201         return $this->morphMany(Deletion::class, 'deletable');
202     }
203
204     /**
205      * Get the references pointing from this entity to other items.
206      */
207     public function referencesFrom(): MorphMany
208     {
209         return $this->morphMany(Reference::class, 'from');
210     }
211
212     /**
213      * Get the references pointing to this entity from other items.
214      */
215     public function referencesTo(): MorphMany
216     {
217         return $this->morphMany(Reference::class, 'to');
218     }
219
220     /**
221      * Check if this instance or class is a certain type of entity.
222      * Examples of $type are 'page', 'book', 'chapter'.
223      *
224      * @deprecated Use instanceof instead.
225      */
226     public static function isA(string $type): bool
227     {
228         return static::getType() === strtolower($type);
229     }
230
231     /**
232      * Get the entity type as a simple lowercase word.
233      */
234     public static function getType(): string
235     {
236         $className = array_slice(explode('\\', static::class), -1, 1)[0];
237
238         return strtolower($className);
239     }
240
241     /**
242      * Gets a limited-length version of the entities name.
243      */
244     public function getShortName(int $length = 25): string
245     {
246         if (mb_strlen($this->name) <= $length) {
247             return $this->name;
248         }
249
250         return mb_substr($this->name, 0, $length - 3) . '...';
251     }
252
253     /**
254      * Get an excerpt of this entity's descriptive content to the specified length.
255      */
256     public function getExcerpt(int $length = 100): string
257     {
258         $text = $this->{$this->textField} ?? '';
259
260         if (mb_strlen($text) > $length) {
261             $text = mb_substr($text, 0, $length - 3) . '...';
262         }
263
264         return trim($text);
265     }
266
267     /**
268      * Get the url of this entity.
269      */
270     abstract public function getUrl(string $path = '/'): string;
271
272     /**
273      * Get the parent entity if existing.
274      * This is the "static" parent and does not include dynamic
275      * relations such as shelves to books.
276      */
277     public function getParent(): ?self
278     {
279         if ($this instanceof Page) {
280             return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
281         }
282         if ($this instanceof Chapter) {
283             return $this->book()->withTrashed()->first();
284         }
285
286         return null;
287     }
288
289     /**
290      * Rebuild the permissions for this entity.
291      */
292     public function rebuildPermissions()
293     {
294         app()->make(JointPermissionBuilder::class)->rebuildForEntity(clone $this);
295     }
296
297     /**
298      * Index the current entity for search.
299      */
300     public function indexForSearch()
301     {
302         app()->make(SearchIndex::class)->indexEntity(clone $this);
303     }
304
305     /**
306      * {@inheritdoc}
307      */
308     public function refreshSlug(): string
309     {
310         $this->slug = app()->make(SlugGenerator::class)->generate($this);
311
312         return $this->slug;
313     }
314
315     /**
316      * {@inheritdoc}
317      */
318     public function favourites(): MorphMany
319     {
320         return $this->morphMany(Favourite::class, 'favouritable');
321     }
322
323     /**
324      * Check if the entity is a favourite of the current user.
325      */
326     public function isFavourite(): bool
327     {
328         return $this->favourites()
329             ->where('user_id', '=', user()->id)
330             ->exists();
331     }
332
333     /**
334      * {@inheritdoc}
335      */
336     public function logDescriptor(): string
337     {
338         return "({$this->id}) {$this->name}";
339     }
340 }