]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/Entity.php
Added test for logical-theme-system command registration
[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\Sluggable;
18 use BookStack\Interfaces\Viewable;
19 use BookStack\Model;
20 use BookStack\Traits\HasCreatorAndUpdater;
21 use BookStack\Traits\HasOwner;
22 use Carbon\Carbon;
23 use Illuminate\Database\Eloquent\Builder;
24 use Illuminate\Database\Eloquent\Collection;
25 use Illuminate\Database\Eloquent\Relations\MorphMany;
26 use Illuminate\Database\Eloquent\SoftDeletes;
27
28 /**
29  * Class Entity
30  * The base class for book-like items such as pages, chapters & books.
31  * This is not a database model in itself but extended.
32  *
33  * @property int        $id
34  * @property string     $name
35  * @property string     $slug
36  * @property Carbon     $created_at
37  * @property Carbon     $updated_at
38  * @property int        $created_by
39  * @property int        $updated_by
40  * @property bool       $restricted
41  * @property Collection $tags
42  *
43  * @method static Entity|Builder visible()
44  * @method static Entity|Builder hasPermission(string $permission)
45  * @method static Builder withLastView()
46  * @method static Builder withViewCount()
47  */
48 abstract class Entity extends Model implements Sluggable, Favouritable, Viewable, Deletable
49 {
50     use SoftDeletes;
51     use HasCreatorAndUpdater;
52     use HasOwner;
53
54     /**
55      * @var string - Name of property where the main text content is found
56      */
57     public $textField = 'description';
58
59     /**
60      * @var float - Multiplier for search indexing.
61      */
62     public $searchFactor = 1.0;
63
64     /**
65      * Get the entities that are visible to the current user.
66      */
67     public function scopeVisible(Builder $query): Builder
68     {
69         return $this->scopeHasPermission($query, 'view');
70     }
71
72     /**
73      * Scope the query to those entities that the current user has the given permission for.
74      */
75     public function scopeHasPermission(Builder $query, string $permission)
76     {
77         return Permissions::restrictEntityQuery($query, $permission);
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->isA('chapter') || $entity->isA('page')) && $this->isA('book')) {
125             return $entity->book_id === $this->id;
126         }
127
128         if ($entity->isA('page') && $this->isA('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, 'entity')
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, 'restrictable');
184     }
185
186     /**
187      * Check if this entity has a specific restriction set against it.
188      */
189     public function hasRestriction(int $role_id, string $action): bool
190     {
191         return $this->permissions()->where('role_id', '=', $role_id)
192             ->where('action', '=', $action)->count() > 0;
193     }
194
195     /**
196      * Get the entity jointPermissions this is connected to.
197      */
198     public function jointPermissions(): MorphMany
199     {
200         return $this->morphMany(JointPermission::class, 'entity');
201     }
202
203     /**
204      * Get the related delete records for this entity.
205      */
206     public function deletions(): MorphMany
207     {
208         return $this->morphMany(Deletion::class, 'deletable');
209     }
210
211     /**
212      * Check if this instance or class is a certain type of entity.
213      * Examples of $type are 'page', 'book', 'chapter'.
214      * @deprecated Use instanceof instead.
215      */
216     public static function isA(string $type): bool
217     {
218         return static::getType() === strtolower($type);
219     }
220
221     /**
222      * Get the entity type as a simple lowercase word.
223      */
224     public static function getType(): string
225     {
226         $className = array_slice(explode('\\', static::class), -1, 1)[0];
227
228         return strtolower($className);
229     }
230
231     /**
232      * Gets a limited-length version of the entities name.
233      */
234     public function getShortName(int $length = 25): string
235     {
236         if (mb_strlen($this->name) <= $length) {
237             return $this->name;
238         }
239
240         return mb_substr($this->name, 0, $length - 3) . '...';
241     }
242
243     /**
244      * Get an excerpt of this entity's descriptive content to the specified length.
245      */
246     public function getExcerpt(int $length = 100): string
247     {
248         $text = $this->{$this->textField} ?? '';
249
250         if (mb_strlen($text) > $length) {
251             $text = mb_substr($text, 0, $length - 3) . '...';
252         }
253
254         return trim($text);
255     }
256
257     /**
258      * Get the url of this entity.
259      */
260     abstract public function getUrl(string $path = '/'): string;
261
262     /**
263      * Get the parent entity if existing.
264      * This is the "static" parent and does not include dynamic
265      * relations such as shelves to books.
266      */
267     public function getParent(): ?self
268     {
269         if ($this instanceof Page) {
270             return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
271         }
272         if ($this instanceof Chapter) {
273             return $this->book()->withTrashed()->first();
274         }
275
276         return null;
277     }
278
279     /**
280      * Rebuild the permissions for this entity.
281      */
282     public function rebuildPermissions()
283     {
284         /** @noinspection PhpUnhandledExceptionInspection */
285         Permissions::buildJointPermissionsForEntity(clone $this);
286     }
287
288     /**
289      * Index the current entity for search.
290      */
291     public function indexForSearch()
292     {
293         app(SearchIndex::class)->indexEntity(clone $this);
294     }
295
296     /**
297      * {@inheritdoc}
298      */
299     public function refreshSlug(): string
300     {
301         $this->slug = app(SlugGenerator::class)->generate($this);
302
303         return $this->slug;
304     }
305
306     /**
307      * {@inheritdoc}
308      */
309     public function favourites(): MorphMany
310     {
311         return $this->morphMany(Favourite::class, 'favouritable');
312     }
313
314     /**
315      * Check if the entity is a favourite of the current user.
316      */
317     public function isFavourite(): bool
318     {
319         return $this->favourites()
320             ->where('user_id', '=', user()->id)
321             ->exists();
322     }
323 }