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