3 namespace BookStack\Entities\Models;
5 use BookStack\Activity\Models\Activity;
6 use BookStack\Activity\Models\Comment;
7 use BookStack\Activity\Models\Favouritable;
8 use BookStack\Activity\Models\Favourite;
9 use BookStack\Activity\Models\Loggable;
10 use BookStack\Activity\Models\Tag;
11 use BookStack\Activity\Models\View;
12 use BookStack\Activity\Models\Viewable;
13 use BookStack\Activity\Models\Watch;
14 use BookStack\App\Model;
15 use BookStack\App\Sluggable;
16 use BookStack\Entities\Tools\SlugGenerator;
17 use BookStack\Permissions\JointPermissionBuilder;
18 use BookStack\Permissions\Models\EntityPermission;
19 use BookStack\Permissions\Models\JointPermission;
20 use BookStack\Permissions\PermissionApplicator;
21 use BookStack\References\Reference;
22 use BookStack\Search\SearchIndex;
23 use BookStack\Search\SearchTerm;
24 use BookStack\Users\Models\HasCreatorAndUpdater;
25 use BookStack\Users\Models\HasOwner;
27 use Illuminate\Database\Eloquent\Builder;
28 use Illuminate\Database\Eloquent\Collection;
29 use Illuminate\Database\Eloquent\Relations\BelongsTo;
30 use Illuminate\Database\Eloquent\Relations\MorphMany;
31 use Illuminate\Database\Eloquent\SoftDeletes;
35 * The base class for book-like items such as pages, chapters & books.
36 * This is not a database model in itself but extended.
39 * @property string $name
40 * @property string $slug
41 * @property Carbon $created_at
42 * @property Carbon $updated_at
43 * @property Carbon $deleted_at
44 * @property int $created_by
45 * @property int $updated_by
46 * @property Collection $tags
48 * @method static Entity|Builder visible()
49 * @method static Builder withLastView()
50 * @method static Builder withViewCount()
52 abstract class Entity extends Model implements Sluggable, Favouritable, Viewable, Deletable, Loggable
55 use HasCreatorAndUpdater;
59 * @var string - Name of property where the main text content is found
61 public string $textField = 'description';
64 * @var string - Name of the property where the main HTML content is found
66 public string $htmlField = 'description_html';
69 * @var float - Multiplier for search indexing.
71 public float $searchFactor = 1.0;
74 * Get the entities that are visible to the current user.
76 public function scopeVisible(Builder $query): Builder
78 return app()->make(PermissionApplicator::class)->restrictEntityQuery($query);
82 * Query scope to get the last view from the current user.
84 public function scopeWithLastView(Builder $query)
86 $viewedAtQuery = View::query()->select('updated_at')
87 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
88 ->where('viewable_type', '=', $this->getMorphClass())
89 ->where('user_id', '=', user()->id)
92 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
96 * Query scope to get the total view count of the entities.
98 public function scopeWithViewCount(Builder $query)
100 $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
101 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
102 ->where('viewable_type', '=', $this->getMorphClass())->take(1);
104 $query->addSelect(['view_count' => $viewCountQuery]);
108 * Compares this entity to another given entity.
109 * Matches by comparing class and id.
111 public function matches(self $entity): bool
113 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
117 * Checks if the current entity matches or contains the given.
119 public function matchesOrContains(self $entity): bool
121 if ($this->matches($entity)) {
125 if (($entity instanceof BookChild) && $this instanceof Book) {
126 return $entity->book_id === $this->id;
129 if ($entity instanceof Page && $this instanceof Chapter) {
130 return $entity->chapter_id === $this->id;
137 * Gets the activity objects for this entity.
139 public function activity(): MorphMany
141 return $this->morphMany(Activity::class, 'loggable')
142 ->orderBy('created_at', 'desc');
146 * Get View objects for this entity.
148 public function views(): MorphMany
150 return $this->morphMany(View::class, 'viewable');
154 * Get the Tag models that have been user assigned to this entity.
156 public function tags(): MorphMany
158 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
162 * Get the comments for an entity.
164 public function comments(bool $orderByCreated = true): MorphMany
166 $query = $this->morphMany(Comment::class, 'entity');
168 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
172 * Get the related search terms.
174 public function searchTerms(): MorphMany
176 return $this->morphMany(SearchTerm::class, 'entity');
180 * Get this entities restrictions.
182 public function permissions(): MorphMany
184 return $this->morphMany(EntityPermission::class, 'entity');
188 * Check if this entity has a specific restriction set against it.
190 public function hasPermissions(): bool
192 return $this->permissions()->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 * Get the references pointing from this entity to other items.
214 public function referencesFrom(): MorphMany
216 return $this->morphMany(Reference::class, 'from');
220 * Get the references pointing to this entity from other items.
222 public function referencesTo(): MorphMany
224 return $this->morphMany(Reference::class, 'to');
228 * Check if this instance or class is a certain type of entity.
229 * Examples of $type are 'page', 'book', 'chapter'.
231 * @deprecated Use instanceof instead.
233 public static function isA(string $type): bool
235 return static::getType() === strtolower($type);
239 * Get the entity type as a simple lowercase word.
241 public static function getType(): string
243 $className = array_slice(explode('\\', static::class), -1, 1)[0];
245 return strtolower($className);
249 * Gets a limited-length version of the entities name.
251 public function getShortName(int $length = 25): string
253 if (mb_strlen($this->name) <= $length) {
257 return mb_substr($this->name, 0, $length - 3) . '...';
261 * Get an excerpt of this entity's descriptive content to the specified length.
263 public function getExcerpt(int $length = 100): string
265 $text = $this->{$this->textField} ?? '';
267 if (mb_strlen($text) > $length) {
268 $text = mb_substr($text, 0, $length - 3) . '...';
275 * Get the url of this entity.
277 abstract public function getUrl(string $path = '/'): string;
280 * Get the parent entity if existing.
281 * This is the "static" parent and does not include dynamic
282 * relations such as shelves to books.
284 public function getParent(): ?self
286 if ($this instanceof Page) {
287 /** @var BelongsTo<Chapter|Book, Page> $builder */
288 $builder = $this->chapter_id ? $this->chapter() : $this->book();
289 return $builder->withTrashed()->first();
291 if ($this instanceof Chapter) {
292 /** @var BelongsTo<Book, Page> $builder */
293 $builder = $this->book();
294 return $builder->withTrashed()->first();
301 * Rebuild the permissions for this entity.
303 public function rebuildPermissions(): void
305 app()->make(JointPermissionBuilder::class)->rebuildForEntity(clone $this);
309 * Index the current entity for search.
311 public function indexForSearch(): void
313 app()->make(SearchIndex::class)->indexEntity(clone $this);
319 public function refreshSlug(): string
321 $this->slug = app()->make(SlugGenerator::class)->generate($this);
329 public function favourites(): MorphMany
331 return $this->morphMany(Favourite::class, 'favouritable');
335 * Check if the entity is a favourite of the current user.
337 public function isFavourite(): bool
339 return $this->favourites()
340 ->where('user_id', '=', user()->id)
345 * Get the related watches for this entity.
347 public function watches(): MorphMany
349 return $this->morphMany(Watch::class, 'watchable');
355 public function logDescriptor(): string
357 return "({$this->id}) {$this->name}";