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