]> BookStack Code Mirror - bookstack/blob - app/Entities/Models/Entity.php
Merge branch 'create-content-meta-tags' of https://github.com/james-geiger/BookStack...
[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\Favourite;
6 use BookStack\Actions\Tag;
7 use BookStack\Actions\View;
8 use BookStack\Auth\Permissions\EntityPermission;
9 use BookStack\Auth\Permissions\JointPermission;
10 use BookStack\Entities\Tools\SearchIndex;
11 use BookStack\Entities\Tools\SlugGenerator;
12 use BookStack\Facades\Permissions;
13 use BookStack\Interfaces\Favouritable;
14 use BookStack\Interfaces\Sluggable;
15 use BookStack\Interfaces\Viewable;
16 use BookStack\Model;
17 use BookStack\Traits\HasCreatorAndUpdater;
18 use BookStack\Traits\HasOwner;
19 use Carbon\Carbon;
20 use Illuminate\Database\Eloquent\Builder;
21 use Illuminate\Database\Eloquent\Collection;
22 use Illuminate\Database\Eloquent\Relations\MorphMany;
23 use Illuminate\Database\Eloquent\SoftDeletes;
24
25 /**
26  * Class Entity
27  * The base class for book-like items such as pages, chapters & books.
28  * This is not a database model in itself but extended.
29  *
30  * @property int $id
31  * @property string $name
32  * @property string $slug
33  * @property Carbon $created_at
34  * @property Carbon $updated_at
35  * @property int $created_by
36  * @property int $updated_by
37  * @property boolean $restricted
38  * @property Collection $tags
39  * @method static Entity|Builder visible()
40  * @method static Entity|Builder hasPermission(string $permission)
41  * @method static Builder withLastView()
42  * @method static Builder withViewCount()
43  */
44 abstract class Entity extends Model implements Sluggable, Favouritable, Viewable
45 {
46     use SoftDeletes;
47     use HasCreatorAndUpdater;
48     use HasOwner;
49
50     /**
51      * @var string - Name of property where the main text content is found
52      */
53     public $textField = 'description';
54
55     /**
56      * @var float - Multiplier for search indexing.
57      */
58     public $searchFactor = 1.0;
59
60     /**
61      * Get the entities that are visible to the current user.
62      */
63     public function scopeVisible(Builder $query): Builder
64     {
65         return $this->scopeHasPermission($query, 'view');
66     }
67
68     /**
69      * Scope the query to those entities that the current user has the given permission for.
70      */
71     public function scopeHasPermission(Builder $query, string $permission)
72     {
73         return Permissions::restrictEntityQuery($query, $permission);
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(Entity $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(Entity $entity): bool
115     {
116         if ($this->matches($entity)) {
117             return true;
118         }
119
120         if (($entity->isA('chapter') || $entity->isA('page')) && $this->isA('book')) {
121             return $entity->book_id === $this->id;
122         }
123
124         if ($entity->isA('page') && $this->isA('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         return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
163     }
164
165     /**
166      * Get the related search terms.
167      */
168     public function searchTerms(): MorphMany
169     {
170         return $this->morphMany(SearchTerm::class, 'entity');
171     }
172
173     /**
174      * Get this entities restrictions.
175      */
176     public function permissions(): MorphMany
177     {
178         return $this->morphMany(EntityPermission::class, 'restrictable');
179     }
180
181     /**
182      * Check if this entity has a specific restriction set against it.
183      */
184     public function hasRestriction(int $role_id, string $action): bool
185     {
186         return $this->permissions()->where('role_id', '=', $role_id)
187             ->where('action', '=', $action)->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 related delete records for this entity.
200      */
201     public function deletions(): MorphMany
202     {
203         return $this->morphMany(Deletion::class, 'deletable');
204     }
205
206     /**
207      * Check if this instance or class is a certain type of entity.
208      * Examples of $type are 'page', 'book', 'chapter'
209      */
210     public static function isA(string $type): bool
211     {
212         return static::getType() === strtolower($type);
213     }
214
215     /**
216      * Get the entity type as a simple lowercase word.
217      */
218     public static function getType(): string
219     {
220         $className = array_slice(explode('\\', static::class), -1, 1)[0];
221         return strtolower($className);
222     }
223
224     /**
225      * Gets a limited-length version of the entities name.
226      */
227     public function getShortName(int $length = 25): string
228     {
229         if (mb_strlen($this->name) <= $length) {
230             return $this->name;
231         }
232         return mb_substr($this->name, 0, $length - 3) . '...';
233     }
234
235     /**
236      * Get the body text of this entity.
237      */
238     public function getText(): string
239     {
240         return $this->{$this->textField} ?? '';
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->getText();
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(): ?Entity
268     {
269         if ($this->isA('page')) {
270             return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
271         }
272         if ($this->isA('chapter')) {
273             return $this->book()->withTrashed()->first();
274         }
275         return null;
276     }
277
278     /**
279      * Rebuild the permissions for this entity.
280      */
281     public function rebuildPermissions()
282     {
283         /** @noinspection PhpUnhandledExceptionInspection */
284         Permissions::buildJointPermissionsForEntity(clone $this);
285     }
286
287     /**
288      * Index the current entity for search
289      */
290     public function indexForSearch()
291     {
292         app(SearchIndex::class)->indexEntity(clone $this);
293     }
294
295     /**
296      * @inheritdoc
297      */
298     public function refreshSlug(): string
299     {
300         $this->slug = app(SlugGenerator::class)->generate($this);
301         return $this->slug;
302     }
303
304     /**
305      * @inheritdoc
306      */
307     public function favourites(): MorphMany
308     {
309         return $this->morphMany(Favourite::class, 'favouritable');
310     }
311
312     /**
313      * Check if the entity is a favourite of the current user.
314      */
315     public function isFavourite(): bool
316     {
317         return $this->favourites()
318             ->where('user_id', '=', user()->id)
319             ->exists();
320     }
321 }