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