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\SluggableInterface;
16 use BookStack\Permissions\JointPermissionBuilder;
17 use BookStack\Permissions\Models\EntityPermission;
18 use BookStack\Permissions\Models\JointPermission;
19 use BookStack\Permissions\PermissionApplicator;
20 use BookStack\References\Reference;
21 use BookStack\Search\SearchIndex;
22 use BookStack\Search\SearchTerm;
23 use BookStack\Users\Models\HasCreatorAndUpdater;
24 use BookStack\Users\Models\OwnableInterface;
25 use BookStack\Users\Models\User;
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\HasOne;
31 use Illuminate\Database\Eloquent\Relations\MorphMany;
32 use Illuminate\Database\Eloquent\SoftDeletes;
36 * The base class for book-like items such as pages, chapters and books.
37 * This is not a database model in itself but extended.
40 * @property string $type
41 * @property string $name
42 * @property string $slug
43 * @property Carbon $created_at
44 * @property Carbon $updated_at
45 * @property Carbon $deleted_at
46 * @property int|null $created_by
47 * @property int|null $updated_by
48 * @property int|null $owned_by
49 * @property Collection $tags
51 * @method static Entity|Builder visible()
52 * @method static Builder withLastView()
53 * @method static Builder withViewCount()
55 abstract class Entity extends Model implements
64 use HasCreatorAndUpdater;
67 * @var string - Name of property where the main text content is found
69 public string $textField = 'description';
72 * @var string - Name of the property where the main HTML content is found
74 public string $htmlField = 'description_html';
77 * @var float - Multiplier for search indexing.
79 public float $searchFactor = 1.0;
82 * Set the table to be that used by all entities.
84 protected $table = 'entities';
87 * Set a custom query builder for entities.
89 protected static string $builder = EntityQueryBuilder::class;
91 public static array $commonFields = [
108 * Override the save method to also save the contents for convenience.
110 public function save(array $options = []): bool
112 /** @var EntityPageData|EntityContainerData $contents */
113 $contents = $this->relatedData()->firstOrNew();
114 $contentFields = $this->getContentsAttributes();
116 foreach ($contentFields as $key => $value) {
117 $contents->setAttribute($key, $value);
118 unset($this->attributes[$key]);
121 $this->setAttribute('type', $this->getMorphClass());
122 $result = parent::save($options);
123 $contentsResult = true;
125 if ($result && $contents->isDirty()) {
126 $contentsFillData = $contents instanceof EntityPageData ? ['page_id' => $this->id] : ['entity_id' => $this->id, 'entity_type' => $this->getMorphClass()];
127 $contents->forceFill($contentsFillData);
128 $contentsResult = $contents->save();
132 $this->forceFill($contentFields);
134 return $result && $contentsResult;
138 * Check if this item is a container item.
140 public function isContainer(): bool
142 return $this instanceof Bookshelf ||
143 $this instanceof Book ||
144 $this instanceof Chapter;
148 * Get the entities that are visible to the current user.
150 public function scopeVisible(Builder $query): Builder
152 return app()->make(PermissionApplicator::class)->restrictEntityQuery($query);
156 * Query scope to get the last view from the current user.
158 public function scopeWithLastView(Builder $query)
160 $viewedAtQuery = View::query()->select('updated_at')
161 ->whereColumn('viewable_id', '=', 'entities.id')
162 ->whereColumn('viewable_type', '=', 'entities.type')
163 ->where('user_id', '=', user()->id)
166 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
170 * Query scope to get the total view count of the entities.
172 public function scopeWithViewCount(Builder $query): void
174 $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
175 ->whereColumn('viewable_id', '=', 'entities.id')
176 ->whereColumn('viewable_type', '=', 'entities.type')
179 $query->addSelect(['view_count' => $viewCountQuery]);
183 * Compares this entity to another given entity.
184 * Matches by comparing class and id.
186 public function matches(self $entity): bool
188 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
192 * Checks if the current entity matches or contains the given.
194 public function matchesOrContains(self $entity): bool
196 if ($this->matches($entity)) {
200 if (($entity instanceof BookChild) && $this instanceof Book) {
201 return $entity->book_id === $this->id;
204 if ($entity instanceof Page && $this instanceof Chapter) {
205 return $entity->chapter_id === $this->id;
212 * Gets the activity objects for this entity.
214 public function activity(): MorphMany
216 return $this->morphMany(Activity::class, 'loggable')
217 ->orderBy('created_at', 'desc');
221 * Get View objects for this entity.
223 public function views(): MorphMany
225 return $this->morphMany(View::class, 'viewable');
229 * Get the Tag models that have been user assigned to this entity.
231 public function tags(): MorphMany
233 return $this->morphMany(Tag::class, 'entity')
234 ->orderBy('order', 'asc');
238 * Get the comments for an entity.
239 * @return MorphMany<Comment, $this>
241 public function comments(bool $orderByCreated = true): MorphMany
243 $query = $this->morphMany(Comment::class, 'commentable');
245 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
249 * Get the related search terms.
251 public function searchTerms(): MorphMany
253 return $this->morphMany(SearchTerm::class, 'entity');
257 * Get this entities assigned permissions.
259 public function permissions(): MorphMany
261 return $this->morphMany(EntityPermission::class, 'entity');
265 * Check if this entity has a specific restriction set against it.
267 public function hasPermissions(): bool
269 return $this->permissions()->count() > 0;
273 * Get the entity jointPermissions this is connected to.
275 public function jointPermissions(): MorphMany
277 return $this->morphMany(JointPermission::class, 'entity');
281 * Get the user who owns this entity.
282 * @return BelongsTo<User, $this>
284 public function ownedBy(): BelongsTo
286 return $this->belongsTo(User::class, 'owned_by');
289 public function getOwnerFieldName(): string
295 * Get the related delete records for this entity.
297 public function deletions(): MorphMany
299 return $this->morphMany(Deletion::class, 'deletable');
303 * Get the references pointing from this entity to other items.
305 public function referencesFrom(): MorphMany
307 return $this->morphMany(Reference::class, 'from');
311 * Get the references pointing to this entity from other items.
313 public function referencesTo(): MorphMany
315 return $this->morphMany(Reference::class, 'to');
319 * Check if this instance or class is a certain type of entity.
320 * Examples of $type are 'page', 'book', 'chapter'.
322 * @deprecated Use instanceof instead.
324 public static function isA(string $type): bool
326 return static::getType() === strtolower($type);
330 * Get the entity type as a simple lowercase word.
332 public static function getType(): string
334 $className = array_slice(explode('\\', static::class), -1, 1)[0];
336 return strtolower($className);
340 * Gets a limited-length version of the entity name.
342 public function getShortName(int $length = 25): string
344 if (mb_strlen($this->name) <= $length) {
348 return mb_substr($this->name, 0, $length - 3) . '...';
352 * Get an excerpt of this entity's descriptive content to the specified length.
354 public function getExcerpt(int $length = 100): string
356 $text = $this->{$this->textField} ?? '';
358 if (mb_strlen($text) > $length) {
359 $text = mb_substr($text, 0, $length - 3) . '...';
366 * Get the url of this entity.
368 abstract public function getUrl(string $path = '/'): string;
371 * Get the parent entity if existing.
372 * This is the "static" parent and does not include dynamic
373 * relations such as shelves to books.
375 public function getParent(): ?self
377 if ($this instanceof Page) {
378 /** @var BelongsTo<Chapter|Book, Page> $builder */
379 $builder = $this->chapter_id ? $this->chapter() : $this->book();
380 return $builder->withTrashed()->first();
382 if ($this instanceof Chapter) {
383 /** @var BelongsTo<Book, Page> $builder */
384 $builder = $this->book();
385 return $builder->withTrashed()->first();
392 * Rebuild the permissions for this entity.
394 public function rebuildPermissions(): void
396 app()->make(JointPermissionBuilder::class)->rebuildForEntity(clone $this);
400 * Index the current entity for search.
402 public function indexForSearch(): void
404 app()->make(SearchIndex::class)->indexEntity(clone $this);
410 public function favourites(): MorphMany
412 return $this->morphMany(Favourite::class, 'favouritable');
416 * Check if the entity is a favourite of the current user.
418 public function isFavourite(): bool
420 return $this->favourites()
421 ->where('user_id', '=', user()->id)
426 * Get the related watches for this entity.
428 public function watches(): MorphMany
430 return $this->morphMany(Watch::class, 'watchable');
434 * Get the related slug history for this entity.
436 public function slugHistory(): MorphMany
438 return $this->morphMany(SlugHistory::class, 'sluggable');
444 public function logDescriptor(): string
446 return "({$this->id}) {$this->name}";
450 * @return HasOne<covariant (EntityContainerData|EntityPageData), $this>
452 abstract public function relatedData(): HasOne;
455 * Get the attributes that are intended for the related contents model.
456 * @return array<string, mixed>
458 protected function getContentsAttributes(): array
461 $contentModel = $this instanceof Page ? EntityPageData::class : EntityContainerData::class;
463 foreach ($this->attributes as $key => $value) {
464 if (in_array($key, $contentModel::$fields)) {
465 $contentFields[$key] = $value;
469 return $contentFields;
473 * Create a new instance for the given entity type.
475 public static function instanceFromType(string $type): self
477 return match ($type) {
478 'page' => new Page(),
479 'chapter' => new Chapter(),
480 'book' => new Book(),
481 'bookshelf' => new Bookshelf(),