3 namespace BookStack\Entities\Models;
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\Favouritable;
16 use BookStack\Interfaces\Sluggable;
17 use BookStack\Interfaces\Viewable;
19 use BookStack\Traits\HasCreatorAndUpdater;
20 use BookStack\Traits\HasOwner;
22 use Illuminate\Database\Eloquent\Builder;
23 use Illuminate\Database\Eloquent\Collection;
24 use Illuminate\Database\Eloquent\Relations\MorphMany;
25 use Illuminate\Database\Eloquent\SoftDeletes;
29 * The base class for book-like items such as pages, chapters & books.
30 * This is not a database model in itself but extended.
33 * @property string $name
34 * @property string $slug
35 * @property Carbon $created_at
36 * @property Carbon $updated_at
37 * @property int $created_by
38 * @property int $updated_by
39 * @property bool $restricted
40 * @property Collection $tags
42 * @method static Entity|Builder visible()
43 * @method static Entity|Builder hasPermission(string $permission)
44 * @method static Builder withLastView()
45 * @method static Builder withViewCount()
47 abstract class Entity extends Model implements Sluggable, Favouritable, Viewable
50 use HasCreatorAndUpdater;
54 * @var string - Name of property where the main text content is found
56 public $textField = 'description';
59 * @var float - Multiplier for search indexing.
61 public $searchFactor = 1.0;
64 * Get the entities that are visible to the current user.
66 public function scopeVisible(Builder $query): Builder
68 return $this->scopeHasPermission($query, 'view');
72 * Scope the query to those entities that the current user has the given permission for.
74 public function scopeHasPermission(Builder $query, string $permission)
76 return Permissions::restrictEntityQuery($query, $permission);
80 * Query scope to get the last view from the current user.
82 public function scopeWithLastView(Builder $query)
84 $viewedAtQuery = View::query()->select('updated_at')
85 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
86 ->where('viewable_type', '=', $this->getMorphClass())
87 ->where('user_id', '=', user()->id)
90 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
94 * Query scope to get the total view count of the entities.
96 public function scopeWithViewCount(Builder $query)
98 $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
99 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
100 ->where('viewable_type', '=', $this->getMorphClass())->take(1);
102 $query->addSelect(['view_count' => $viewCountQuery]);
106 * Compares this entity to another given entity.
107 * Matches by comparing class and id.
109 public function matches(Entity $entity): bool
111 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
115 * Checks if the current entity matches or contains the given.
117 public function matchesOrContains(Entity $entity): bool
119 if ($this->matches($entity)) {
123 if (($entity->isA('chapter') || $entity->isA('page')) && $this->isA('book')) {
124 return $entity->book_id === $this->id;
127 if ($entity->isA('page') && $this->isA('chapter')) {
128 return $entity->chapter_id === $this->id;
135 * Gets the activity objects for this entity.
137 public function activity(): MorphMany
139 return $this->morphMany(Activity::class, 'entity')
140 ->orderBy('created_at', 'desc');
144 * Get View objects for this entity.
146 public function views(): MorphMany
148 return $this->morphMany(View::class, 'viewable');
152 * Get the Tag models that have been user assigned to this entity.
154 public function tags(): MorphMany
156 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
160 * Get the comments for an entity.
162 public function comments(bool $orderByCreated = true): MorphMany
164 $query = $this->morphMany(Comment::class, 'entity');
166 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
170 * Get the related search terms.
172 public function searchTerms(): MorphMany
174 return $this->morphMany(SearchTerm::class, 'entity');
178 * Get this entities restrictions.
180 public function permissions(): MorphMany
182 return $this->morphMany(EntityPermission::class, 'restrictable');
186 * Check if this entity has a specific restriction set against it.
188 public function hasRestriction(int $role_id, string $action): bool
190 return $this->permissions()->where('role_id', '=', $role_id)
191 ->where('action', '=', $action)->count() > 0;
195 * Get the entity jointPermissions this is connected to.
197 public function jointPermissions(): MorphMany
199 return $this->morphMany(JointPermission::class, 'entity');
203 * Get the related delete records for this entity.
205 public function deletions(): MorphMany
207 return $this->morphMany(Deletion::class, 'deletable');
211 * Check if this instance or class is a certain type of entity.
212 * Examples of $type are 'page', 'book', 'chapter'.
214 public static function isA(string $type): bool
216 return static::getType() === strtolower($type);
220 * Get the entity type as a simple lowercase word.
222 public static function getType(): string
224 $className = array_slice(explode('\\', static::class), -1, 1)[0];
226 return strtolower($className);
230 * Gets a limited-length version of the entities name.
232 public function getShortName(int $length = 25): string
234 if (mb_strlen($this->name) <= $length) {
238 return mb_substr($this->name, 0, $length - 3) . '...';
242 * Get the body text of this entity.
244 public function getText(): string
246 return $this->{$this->textField} ?? '';
250 * Get an excerpt of this entity's descriptive content to the specified length.
252 public function getExcerpt(int $length = 100): string
254 $text = $this->getText();
256 if (mb_strlen($text) > $length) {
257 $text = mb_substr($text, 0, $length - 3) . '...';
264 * Get the url of this entity.
266 abstract public function getUrl(string $path = '/'): string;
269 * Get the parent entity if existing.
270 * This is the "static" parent and does not include dynamic
271 * relations such as shelves to books.
273 public function getParent(): ?Entity
275 if ($this instanceof Page) {
276 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
278 if ($this instanceof Chapter) {
279 return $this->book()->withTrashed()->first();
286 * Rebuild the permissions for this entity.
288 public function rebuildPermissions()
290 /** @noinspection PhpUnhandledExceptionInspection */
291 Permissions::buildJointPermissionsForEntity(clone $this);
295 * Index the current entity for search.
297 public function indexForSearch()
299 app(SearchIndex::class)->indexEntity(clone $this);
305 public function refreshSlug(): string
307 $this->slug = app(SlugGenerator::class)->generate($this);
315 public function favourites(): MorphMany
317 return $this->morphMany(Favourite::class, 'favouritable');
321 * Check if the entity is a favourite of the current user.
323 public function isFavourite(): bool
325 return $this->favourites()
326 ->where('user_id', '=', user()->id)