]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/Entity.php
Code cleanup, bug squashing
[bookstack] / app / Entities / Models / Entity.php
1 <?php namespace BookStack\Entities\Models;
2
3 use BookStack\Actions\Activity;
4 use BookStack\Actions\Comment;
5 use BookStack\Actions\Tag;
6 use BookStack\Actions\View;
7 use BookStack\Auth\Permissions\EntityPermission;
8 use BookStack\Auth\Permissions\JointPermission;
9 use BookStack\Entities\Tools\SearchIndex;
10 use BookStack\Entities\Tools\SlugGenerator;
11 use BookStack\Facades\Permissions;
12 use BookStack\Ownable;
13 use Carbon\Carbon;
14 use Illuminate\Database\Eloquent\Builder;
15 use Illuminate\Database\Eloquent\Collection;
16 use Illuminate\Database\Eloquent\Relations\MorphMany;
17 use Illuminate\Database\Eloquent\SoftDeletes;
18
19 /**
20  * Class Entity
21  * The base class for book-like items such as pages, chapters & books.
22  * This is not a database model in itself but extended.
23  *
24  * @property int $id
25  * @property string $name
26  * @property string $slug
27  * @property Carbon $created_at
28  * @property Carbon $updated_at
29  * @property int $created_by
30  * @property int $updated_by
31  * @property boolean $restricted
32  * @property Collection $tags
33  * @method static Entity|Builder visible()
34  * @method static Entity|Builder hasPermission(string $permission)
35  * @method static Builder withLastView()
36  * @method static Builder withViewCount()
37  */
38 abstract class Entity extends Ownable
39 {
40     use SoftDeletes;
41
42     /**
43      * @var string - Name of property where the main text content is found
44      */
45     public $textField = 'description';
46
47     /**
48      * @var float - Multiplier for search indexing.
49      */
50     public $searchFactor = 1.0;
51
52     /**
53      * Get the entities that are visible to the current user.
54      */
55     public function scopeVisible(Builder $query): Builder
56     {
57         return $this->scopeHasPermission($query, 'view');
58     }
59
60     /**
61      * Scope the query to those entities that the current user has the given permission for.
62      */
63     public function scopeHasPermission(Builder $query, string $permission)
64     {
65         return Permissions::restrictEntityQuery($query, $permission);
66     }
67
68     /**
69      * Query scope to get the last view from the current user.
70      */
71     public function scopeWithLastView(Builder $query)
72     {
73         $viewedAtQuery = View::query()->select('updated_at')
74             ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
75             ->where('viewable_type', '=', $this->getMorphClass())
76             ->where('user_id', '=', user()->id)
77             ->take(1);
78
79         return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
80     }
81
82     /**
83      * Query scope to get the total view count of the entities.
84      */
85     public function scopeWithViewCount(Builder $query)
86     {
87         $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
88             ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
89             ->where('viewable_type', '=', $this->getMorphClass())->take(1);
90
91         $query->addSelect(['view_count' => $viewCountQuery]);
92     }
93
94     /**
95      * Compares this entity to another given entity.
96      * Matches by comparing class and id.
97      */
98     public function matches(Entity $entity): bool
99     {
100         return [get_class($this), $this->id] === [get_class($entity), $entity->id];
101     }
102
103     /**
104      * Checks if the current entity matches or contains the given.
105      */
106     public function matchesOrContains(Entity $entity): bool
107     {
108         if ($this->matches($entity)) {
109             return true;
110         }
111
112         if (($entity->isA('chapter') || $entity->isA('page')) && $this->isA('book')) {
113             return $entity->book_id === $this->id;
114         }
115
116         if ($entity->isA('page') && $this->isA('chapter')) {
117             return $entity->chapter_id === $this->id;
118         }
119
120         return false;
121     }
122
123     /**
124      * Gets the activity objects for this entity.
125      */
126     public function activity(): MorphMany
127     {
128         return $this->morphMany(Activity::class, 'entity')
129             ->orderBy('created_at', 'desc');
130     }
131
132     /**
133      * Get View objects for this entity.
134      */
135     public function views(): MorphMany
136     {
137         return $this->morphMany(View::class, 'viewable');
138     }
139
140     /**
141      * Get the Tag models that have been user assigned to this entity.
142      */
143     public function tags(): MorphMany
144     {
145         return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
146     }
147
148     /**
149      * Get the comments for an entity
150      */
151     public function comments(bool $orderByCreated = true): MorphMany
152     {
153         $query = $this->morphMany(Comment::class, 'entity');
154         return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
155     }
156
157     /**
158      * Get the related search terms.
159      */
160     public function searchTerms(): MorphMany
161     {
162         return $this->morphMany(SearchTerm::class, 'entity');
163     }
164
165     /**
166      * Get this entities restrictions.
167      */
168     public function permissions(): MorphMany
169     {
170         return $this->morphMany(EntityPermission::class, 'restrictable');
171     }
172
173     /**
174      * Check if this entity has a specific restriction set against it.
175      */
176     public function hasRestriction(int $role_id, string $action): bool
177     {
178         return $this->permissions()->where('role_id', '=', $role_id)
179             ->where('action', '=', $action)->count() > 0;
180     }
181
182     /**
183      * Get the entity jointPermissions this is connected to.
184      */
185     public function jointPermissions(): MorphMany
186     {
187         return $this->morphMany(JointPermission::class, 'entity');
188     }
189
190     /**
191      * Get the related delete records for this entity.
192      */
193     public function deletions(): MorphMany
194     {
195         return $this->morphMany(Deletion::class, 'deletable');
196     }
197
198     /**
199      * Check if this instance or class is a certain type of entity.
200      * Examples of $type are 'page', 'book', 'chapter'
201      */
202     public static function isA(string $type): bool
203     {
204         return static::getType() === strtolower($type);
205     }
206
207     /**
208      * Get entity type.
209      * @return mixed
210      */
211     public static function getType()
212     {
213         return strtolower(static::getClassName());
214     }
215
216     /**
217      * Gets a limited-length version of the entities name.
218      */
219     public function getShortName(int $length = 25): string
220     {
221         if (mb_strlen($this->name) <= $length) {
222             return $this->name;
223         }
224         return mb_substr($this->name, 0, $length - 3) . '...';
225     }
226
227     /**
228      * Get the body text of this entity.
229      */
230     public function getText(): string
231     {
232         return $this->{$this->textField} ?? '';
233     }
234
235     /**
236      * Get an excerpt of this entity's descriptive content to the specified length.
237      */
238     public function getExcerpt(int $length = 100): string
239     {
240         $text = $this->getText();
241
242         if (mb_strlen($text) > $length) {
243             $text = mb_substr($text, 0, $length-3) . '...';
244         }
245
246         return trim($text);
247     }
248
249     /**
250      * Get the url of this entity
251      */
252     abstract public function getUrl(string $path = '/'): string;
253
254     /**
255      * Get the parent entity if existing.
256      * This is the "static" parent and does not include dynamic
257      * relations such as shelves to books.
258      */
259     public function getParent(): ?Entity
260     {
261         if ($this->isA('page')) {
262             return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
263         }
264         if ($this->isA('chapter')) {
265             return $this->book()->withTrashed()->first();
266         }
267         return null;
268     }
269
270     /**
271      * Rebuild the permissions for this entity.
272      */
273     public function rebuildPermissions()
274     {
275         /** @noinspection PhpUnhandledExceptionInspection */
276         Permissions::buildJointPermissionsForEntity(clone $this);
277     }
278
279     /**
280      * Index the current entity for search
281      */
282     public function indexForSearch()
283     {
284         app(SearchIndex::class)->indexEntity(clone $this);
285     }
286
287     /**
288      * Generate and set a new URL slug for this model.
289      */
290     public function refreshSlug(): string
291     {
292         $this->slug = (new SlugGenerator)->generate($this);
293         return $this->slug;
294     }
295 }