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\MorphMany;
30 use Illuminate\Database\Eloquent\SoftDeletes;
34 * The base class for book-like items such as pages, chapters & books.
35 * This is not a database model in itself but extended.
38 * @property string $name
39 * @property string $slug
40 * @property Carbon $created_at
41 * @property Carbon $updated_at
42 * @property Carbon $deleted_at
43 * @property int $created_by
44 * @property int $updated_by
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 string $textField = 'description';
63 * @var string - Name of the property where the main HTML content is found
65 public string $htmlField = 'description_html';
68 * @var float - Multiplier for search indexing.
70 public float $searchFactor = 1.0;
73 * Get the entities that are visible to the current user.
75 public function scopeVisible(Builder $query): Builder
77 return app()->make(PermissionApplicator::class)->restrictEntityQuery($query);
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 instanceof BookChild) && $this instanceof Book) {
125 return $entity->book_id === $this->id;
128 if ($entity instanceof Page && $this instanceof 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, 'loggable')
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, 'entity');
187 * Check if this entity has a specific restriction set against it.
189 public function hasPermissions(): bool
191 return $this->permissions()->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 * Get the references pointing from this entity to other items.
213 public function referencesFrom(): MorphMany
215 return $this->morphMany(Reference::class, 'from');
219 * Get the references pointing to this entity from other items.
221 public function referencesTo(): MorphMany
223 return $this->morphMany(Reference::class, 'to');
227 * Check if this instance or class is a certain type of entity.
228 * Examples of $type are 'page', 'book', 'chapter'.
230 * @deprecated Use instanceof instead.
232 public static function isA(string $type): bool
234 return static::getType() === strtolower($type);
238 * Get the entity type as a simple lowercase word.
240 public static function getType(): string
242 $className = array_slice(explode('\\', static::class), -1, 1)[0];
244 return strtolower($className);
248 * Gets a limited-length version of the entities name.
250 public function getShortName(int $length = 25): string
252 if (mb_strlen($this->name) <= $length) {
256 return mb_substr($this->name, 0, $length - 3) . '...';
260 * Get an excerpt of this entity's descriptive content to the specified length.
262 public function getExcerpt(int $length = 100): string
264 $text = $this->{$this->textField} ?? '';
266 if (mb_strlen($text) > $length) {
267 $text = mb_substr($text, 0, $length - 3) . '...';
274 * Get the url of this entity.
276 abstract public function getUrl(string $path = '/'): string;
279 * Get the parent entity if existing.
280 * This is the "static" parent and does not include dynamic
281 * relations such as shelves to books.
283 public function getParent(): ?self
285 if ($this instanceof Page) {
286 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
288 if ($this instanceof Chapter) {
289 return $this->book()->withTrashed()->first();
296 * Rebuild the permissions for this entity.
298 public function rebuildPermissions()
300 app()->make(JointPermissionBuilder::class)->rebuildForEntity(clone $this);
304 * Index the current entity for search.
306 public function indexForSearch()
308 app()->make(SearchIndex::class)->indexEntity(clone $this);
314 public function refreshSlug(): string
316 $this->slug = app()->make(SlugGenerator::class)->generate($this);
324 public function favourites(): MorphMany
326 return $this->morphMany(Favourite::class, 'favouritable');
330 * Check if the entity is a favourite of the current user.
332 public function isFavourite(): bool
334 return $this->favourites()
335 ->where('user_id', '=', user()->id)
340 * Get the related watches for this entity.
342 public function watches(): MorphMany
344 return $this->morphMany(Watch::class, 'watchable');
350 public function logDescriptor(): string
352 return "({$this->id}) {$this->name}";