]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/Entity.php
Fixed related permissions query not considering drafts
[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 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, '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      *
215      * @deprecated Use instanceof instead.
216      */
217     public static function isA(string $type): bool
218     {
219         return static::getType() === strtolower($type);
220     }
221
222     /**
223      * Get the entity type as a simple lowercase word.
224      */
225     public static function getType(): string
226     {
227         $className = array_slice(explode('\\', static::class), -1, 1)[0];
228
229         return strtolower($className);
230     }
231
232     /**
233      * Gets a limited-length version of the entities name.
234      */
235     public function getShortName(int $length = 25): string
236     {
237         if (mb_strlen($this->name) <= $length) {
238             return $this->name;
239         }
240
241         return mb_substr($this->name, 0, $length - 3) . '...';
242     }
243
244     /**
245      * Get an excerpt of this entity's descriptive content to the specified length.
246      */
247     public function getExcerpt(int $length = 100): string
248     {
249         $text = $this->{$this->textField} ?? '';
250
251         if (mb_strlen($text) > $length) {
252             $text = mb_substr($text, 0, $length - 3) . '...';
253         }
254
255         return trim($text);
256     }
257
258     /**
259      * Get the url of this entity.
260      */
261     abstract public function getUrl(string $path = '/'): string;
262
263     /**
264      * Get the parent entity if existing.
265      * This is the "static" parent and does not include dynamic
266      * relations such as shelves to books.
267      */
268     public function getParent(): ?self
269     {
270         if ($this instanceof Page) {
271             return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
272         }
273         if ($this instanceof Chapter) {
274             return $this->book()->withTrashed()->first();
275         }
276
277         return null;
278     }
279
280     /**
281      * Rebuild the permissions for this entity.
282      */
283     public function rebuildPermissions()
284     {
285         /** @noinspection PhpUnhandledExceptionInspection */
286         Permissions::buildJointPermissionsForEntity(clone $this);
287     }
288
289     /**
290      * Index the current entity for search.
291      */
292     public function indexForSearch()
293     {
294         app(SearchIndex::class)->indexEntity(clone $this);
295     }
296
297     /**
298      * {@inheritdoc}
299      */
300     public function refreshSlug(): string
301     {
302         $this->slug = app(SlugGenerator::class)->generate($this);
303
304         return $this->slug;
305     }
306
307     /**
308      * {@inheritdoc}
309      */
310     public function favourites(): MorphMany
311     {
312         return $this->morphMany(Favourite::class, 'favouritable');
313     }
314
315     /**
316      * Check if the entity is a favourite of the current user.
317      */
318     public function isFavourite(): bool
319     {
320         return $this->favourites()
321             ->where('user_id', '=', user()->id)
322             ->exists();
323     }
324 }