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