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\References\Reference;
22 use BookStack\Search\SearchIndex;
23 use BookStack\Search\SearchTerm;
24 use BookStack\Traits\HasCreatorAndUpdater;
25 use BookStack\Traits\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 bool $restricted
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 $textField = 'description';
64 * @var float - Multiplier for search indexing.
66 public $searchFactor = 1.0;
69 * Get the entities that are visible to the current user.
71 public function scopeVisible(Builder $query): Builder
73 return app()->make(PermissionApplicator::class)->restrictEntityQuery($query);
77 * Query scope to get the last view from the current user.
79 public function scopeWithLastView(Builder $query)
81 $viewedAtQuery = View::query()->select('updated_at')
82 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
83 ->where('viewable_type', '=', $this->getMorphClass())
84 ->where('user_id', '=', user()->id)
87 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
91 * Query scope to get the total view count of the entities.
93 public function scopeWithViewCount(Builder $query)
95 $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
96 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
97 ->where('viewable_type', '=', $this->getMorphClass())->take(1);
99 $query->addSelect(['view_count' => $viewCountQuery]);
103 * Compares this entity to another given entity.
104 * Matches by comparing class and id.
106 public function matches(self $entity): bool
108 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
112 * Checks if the current entity matches or contains the given.
114 public function matchesOrContains(self $entity): bool
116 if ($this->matches($entity)) {
120 if (($entity instanceof BookChild) && $this instanceof Book) {
121 return $entity->book_id === $this->id;
124 if ($entity instanceof Page && $this instanceof Chapter) {
125 return $entity->chapter_id === $this->id;
132 * Gets the activity objects for this entity.
134 public function activity(): MorphMany
136 return $this->morphMany(Activity::class, 'entity')
137 ->orderBy('created_at', 'desc');
141 * Get View objects for this entity.
143 public function views(): MorphMany
145 return $this->morphMany(View::class, 'viewable');
149 * Get the Tag models that have been user assigned to this entity.
151 public function tags(): MorphMany
153 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
157 * Get the comments for an entity.
159 public function comments(bool $orderByCreated = true): MorphMany
161 $query = $this->morphMany(Comment::class, 'entity');
163 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
167 * Get the related search terms.
169 public function searchTerms(): MorphMany
171 return $this->morphMany(SearchTerm::class, 'entity');
175 * Get this entities restrictions.
177 public function permissions(): MorphMany
179 return $this->morphMany(EntityPermission::class, 'restrictable');
183 * Check if this entity has a specific restriction set against it.
185 public function hasRestriction(int $role_id, string $action): bool
187 return $this->permissions()->where('role_id', '=', $role_id)
188 ->where('action', '=', $action)->count() > 0;
192 * Get the entity jointPermissions this is connected to.
194 public function jointPermissions(): MorphMany
196 return $this->morphMany(JointPermission::class, 'entity');
200 * Get the related delete records for this entity.
202 public function deletions(): MorphMany
204 return $this->morphMany(Deletion::class, 'deletable');
208 * Get the references pointing from this entity to other items.
210 public function referencesFrom(): MorphMany
212 return $this->morphMany(Reference::class, 'from');
216 * Get the references pointing to this entity from other items.
218 public function referencesTo(): MorphMany
220 return $this->morphMany(Reference::class, 'to');
224 * Check if this instance or class is a certain type of entity.
225 * Examples of $type are 'page', 'book', 'chapter'.
227 * @deprecated Use instanceof instead.
229 public static function isA(string $type): bool
231 return static::getType() === strtolower($type);
235 * Get the entity type as a simple lowercase word.
237 public static function getType(): string
239 $className = array_slice(explode('\\', static::class), -1, 1)[0];
241 return strtolower($className);
245 * Gets a limited-length version of the entities name.
247 public function getShortName(int $length = 25): string
249 if (mb_strlen($this->name) <= $length) {
253 return mb_substr($this->name, 0, $length - 3) . '...';
257 * Get an excerpt of this entity's descriptive content to the specified length.
259 public function getExcerpt(int $length = 100): string
261 $text = $this->{$this->textField} ?? '';
263 if (mb_strlen($text) > $length) {
264 $text = mb_substr($text, 0, $length - 3) . '...';
271 * Get the url of this entity.
273 abstract public function getUrl(string $path = '/'): string;
276 * Get the parent entity if existing.
277 * This is the "static" parent and does not include dynamic
278 * relations such as shelves to books.
280 public function getParent(): ?self
282 if ($this instanceof Page) {
283 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
285 if ($this instanceof Chapter) {
286 return $this->book()->withTrashed()->first();
293 * Rebuild the permissions for this entity.
295 public function rebuildPermissions()
297 app()->make(JointPermissionBuilder::class)->rebuildForEntity(clone $this);
301 * Index the current entity for search.
303 public function indexForSearch()
305 app()->make(SearchIndex::class)->indexEntity(clone $this);
311 public function refreshSlug(): string
313 $this->slug = app()->make(SlugGenerator::class)->generate($this);
321 public function favourites(): MorphMany
323 return $this->morphMany(Favourite::class, 'favouritable');
327 * Check if the entity is a favourite of the current user.
329 public function isFavourite(): bool
331 return $this->favourites()
332 ->where('user_id', '=', user()->id)
339 public function logDescriptor(): string
341 return "({$this->id}) {$this->name}";