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\Auth\Permissions\JointPermissionBuilder;
13 use BookStack\Auth\Permissions\PermissionApplicator;
14 use BookStack\Entities\Tools\SlugGenerator;
15 use BookStack\Interfaces\Deletable;
16 use BookStack\Interfaces\Favouritable;
17 use BookStack\Interfaces\Loggable;
18 use BookStack\Interfaces\Sluggable;
19 use BookStack\Interfaces\Viewable;
21 use BookStack\Search\SearchIndex;
22 use BookStack\Search\SearchTerm;
23 use BookStack\Traits\HasCreatorAndUpdater;
24 use BookStack\Traits\HasOwner;
26 use Illuminate\Database\Eloquent\Builder;
27 use Illuminate\Database\Eloquent\Collection;
28 use Illuminate\Database\Eloquent\Relations\MorphMany;
29 use Illuminate\Database\Eloquent\SoftDeletes;
33 * The base class for book-like items such as pages, chapters & books.
34 * This is not a database model in itself but extended.
37 * @property string $name
38 * @property string $slug
39 * @property Carbon $created_at
40 * @property Carbon $updated_at
41 * @property Carbon $deleted_at
42 * @property int $created_by
43 * @property int $updated_by
44 * @property bool $restricted
45 * @property Collection $tags
47 * @method static Entity|Builder visible()
48 * @method static Builder withLastView()
49 * @method static Builder withViewCount()
51 abstract class Entity extends Model implements Sluggable, Favouritable, Viewable, Deletable, Loggable
54 use HasCreatorAndUpdater;
58 * @var string - Name of property where the main text content is found
60 public $textField = 'description';
63 * @var float - Multiplier for search indexing.
65 public $searchFactor = 1.0;
68 * Get the entities that are visible to the current user.
70 public function scopeVisible(Builder $query): Builder
72 return app()->make(PermissionApplicator::class)->restrictEntityQuery($query);
76 * Query scope to get the last view from the current user.
78 public function scopeWithLastView(Builder $query)
80 $viewedAtQuery = View::query()->select('updated_at')
81 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
82 ->where('viewable_type', '=', $this->getMorphClass())
83 ->where('user_id', '=', user()->id)
86 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
90 * Query scope to get the total view count of the entities.
92 public function scopeWithViewCount(Builder $query)
94 $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
95 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
96 ->where('viewable_type', '=', $this->getMorphClass())->take(1);
98 $query->addSelect(['view_count' => $viewCountQuery]);
102 * Compares this entity to another given entity.
103 * Matches by comparing class and id.
105 public function matches(self $entity): bool
107 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
111 * Checks if the current entity matches or contains the given.
113 public function matchesOrContains(self $entity): bool
115 if ($this->matches($entity)) {
119 if (($entity instanceof BookChild) && $this instanceof Book) {
120 return $entity->book_id === $this->id;
123 if ($entity instanceof Page && $this instanceof Chapter) {
124 return $entity->chapter_id === $this->id;
131 * Gets the activity objects for this entity.
133 public function activity(): MorphMany
135 return $this->morphMany(Activity::class, 'entity')
136 ->orderBy('created_at', 'desc');
140 * Get View objects for this entity.
142 public function views(): MorphMany
144 return $this->morphMany(View::class, 'viewable');
148 * Get the Tag models that have been user assigned to this entity.
150 public function tags(): MorphMany
152 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
156 * Get the comments for an entity.
158 public function comments(bool $orderByCreated = true): MorphMany
160 $query = $this->morphMany(Comment::class, 'entity');
162 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
166 * Get the related search terms.
168 public function searchTerms(): MorphMany
170 return $this->morphMany(SearchTerm::class, 'entity');
174 * Get this entities restrictions.
176 public function permissions(): MorphMany
178 return $this->morphMany(EntityPermission::class, 'restrictable');
182 * Check if this entity has a specific restriction set against it.
184 public function hasRestriction(int $role_id, string $action): bool
186 return $this->permissions()->where('role_id', '=', $role_id)
187 ->where('action', '=', $action)->count() > 0;
191 * Get the entity jointPermissions this is connected to.
193 public function jointPermissions(): MorphMany
195 return $this->morphMany(JointPermission::class, 'entity');
199 * Get the related delete records for this entity.
201 public function deletions(): MorphMany
203 return $this->morphMany(Deletion::class, 'deletable');
207 * Check if this instance or class is a certain type of entity.
208 * Examples of $type are 'page', 'book', 'chapter'.
210 * @deprecated Use instanceof instead.
212 public static function isA(string $type): bool
214 return static::getType() === strtolower($type);
218 * Get the entity type as a simple lowercase word.
220 public static function getType(): string
222 $className = array_slice(explode('\\', static::class), -1, 1)[0];
224 return strtolower($className);
228 * Gets a limited-length version of the entities name.
230 public function getShortName(int $length = 25): string
232 if (mb_strlen($this->name) <= $length) {
236 return mb_substr($this->name, 0, $length - 3) . '...';
240 * Get an excerpt of this entity's descriptive content to the specified length.
242 public function getExcerpt(int $length = 100): string
244 $text = $this->{$this->textField} ?? '';
246 if (mb_strlen($text) > $length) {
247 $text = mb_substr($text, 0, $length - 3) . '...';
254 * Get the url of this entity.
256 abstract public function getUrl(string $path = '/'): string;
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.
263 public function getParent(): ?self
265 if ($this instanceof Page) {
266 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
268 if ($this instanceof Chapter) {
269 return $this->book()->withTrashed()->first();
276 * Rebuild the permissions for this entity.
278 public function rebuildPermissions()
280 app()->make(JointPermissionBuilder::class)->rebuildForEntity(clone $this);
284 * Index the current entity for search.
286 public function indexForSearch()
288 app()->make(SearchIndex::class)->indexEntity(clone $this);
294 public function refreshSlug(): string
296 $this->slug = app()->make(SlugGenerator::class)->generate($this);
304 public function favourites(): MorphMany
306 return $this->morphMany(Favourite::class, 'favouritable');
310 * Check if the entity is a favourite of the current user.
312 public function isFavourite(): bool
314 return $this->favourites()
315 ->where('user_id', '=', user()->id)
322 public function logDescriptor(): string
324 return "({$this->id}) {$this->name}";