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\Deletable;
16 use BookStack\Interfaces\Favouritable;
17 use BookStack\Interfaces\Sluggable;
18 use BookStack\Interfaces\Viewable;
20 use BookStack\Traits\HasCreatorAndUpdater;
21 use BookStack\Traits\HasOwner;
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;
30 * The base class for book-like items such as pages, chapters & books.
31 * This is not a database model in itself but extended.
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
43 * @method static Entity|Builder visible()
44 * @method static Entity|Builder hasPermission(string $permission)
45 * @method static Builder withLastView()
46 * @method static Builder withViewCount()
48 abstract class Entity extends Model implements Sluggable, Favouritable, Viewable, Deletable
51 use HasCreatorAndUpdater;
55 * @var string - Name of property where the main text content is found
57 public $textField = 'description';
60 * @var float - Multiplier for search indexing.
62 public $searchFactor = 1.0;
65 * Get the entities that are visible to the current user.
67 public function scopeVisible(Builder $query): Builder
69 return $this->scopeHasPermission($query, 'view');
73 * Scope the query to those entities that the current user has the given permission for.
75 public function scopeHasPermission(Builder $query, string $permission)
77 return Permissions::restrictEntityQuery($query, $permission);
81 * Query scope to get the last view from the current user.
83 public function scopeWithLastView(Builder $query)
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)
91 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
95 * Query scope to get the total view count of the entities.
97 public function scopeWithViewCount(Builder $query)
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);
103 $query->addSelect(['view_count' => $viewCountQuery]);
107 * Compares this entity to another given entity.
108 * Matches by comparing class and id.
110 public function matches(self $entity): bool
112 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
116 * Checks if the current entity matches or contains the given.
118 public function matchesOrContains(self $entity): bool
120 if ($this->matches($entity)) {
124 if (($entity->isA('chapter') || $entity->isA('page')) && $this->isA('book')) {
125 return $entity->book_id === $this->id;
128 if ($entity->isA('page') && $this->isA('chapter')) {
129 return $entity->chapter_id === $this->id;
136 * Gets the activity objects for this entity.
138 public function activity(): MorphMany
140 return $this->morphMany(Activity::class, 'entity')
141 ->orderBy('created_at', 'desc');
145 * Get View objects for this entity.
147 public function views(): MorphMany
149 return $this->morphMany(View::class, 'viewable');
153 * Get the Tag models that have been user assigned to this entity.
155 public function tags(): MorphMany
157 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
161 * Get the comments for an entity.
163 public function comments(bool $orderByCreated = true): MorphMany
165 $query = $this->morphMany(Comment::class, 'entity');
167 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
171 * Get the related search terms.
173 public function searchTerms(): MorphMany
175 return $this->morphMany(SearchTerm::class, 'entity');
179 * Get this entities restrictions.
181 public function permissions(): MorphMany
183 return $this->morphMany(EntityPermission::class, 'restrictable');
187 * Check if this entity has a specific restriction set against it.
189 public function hasRestriction(int $role_id, string $action): bool
191 return $this->permissions()->where('role_id', '=', $role_id)
192 ->where('action', '=', $action)->count() > 0;
196 * Get the entity jointPermissions this is connected to.
198 public function jointPermissions(): MorphMany
200 return $this->morphMany(JointPermission::class, 'entity');
204 * Get the related delete records for this entity.
206 public function deletions(): MorphMany
208 return $this->morphMany(Deletion::class, 'deletable');
212 * Check if this instance or class is a certain type of entity.
213 * Examples of $type are 'page', 'book', 'chapter'.
214 * @deprecated Use instanceof instead.
216 public static function isA(string $type): bool
218 return static::getType() === strtolower($type);
222 * Get the entity type as a simple lowercase word.
224 public static function getType(): string
226 $className = array_slice(explode('\\', static::class), -1, 1)[0];
228 return strtolower($className);
232 * Gets a limited-length version of the entities name.
234 public function getShortName(int $length = 25): string
236 if (mb_strlen($this->name) <= $length) {
240 return mb_substr($this->name, 0, $length - 3) . '...';
244 * Get an excerpt of this entity's descriptive content to the specified length.
246 public function getExcerpt(int $length = 100): string
248 $text = $this->{$this->textField} ?? '';
250 if (mb_strlen($text) > $length) {
251 $text = mb_substr($text, 0, $length - 3) . '...';
258 * Get the url of this entity.
260 abstract public function getUrl(string $path = '/'): string;
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.
267 public function getParent(): ?self
269 if ($this instanceof Page) {
270 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
272 if ($this instanceof Chapter) {
273 return $this->book()->withTrashed()->first();
280 * Rebuild the permissions for this entity.
282 public function rebuildPermissions()
284 /** @noinspection PhpUnhandledExceptionInspection */
285 Permissions::buildJointPermissionsForEntity(clone $this);
289 * Index the current entity for search.
291 public function indexForSearch()
293 app(SearchIndex::class)->indexEntity(clone $this);
299 public function refreshSlug(): string
301 $this->slug = app(SlugGenerator::class)->generate($this);
309 public function favourites(): MorphMany
311 return $this->morphMany(Favourite::class, 'favouritable');
315 * Check if the entity is a favourite of the current user.
317 public function isFavourite(): bool
319 return $this->favourites()
320 ->where('user_id', '=', user()->id)