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\SearchIndex;
15 use BookStack\Entities\Tools\SlugGenerator;
16 use BookStack\Interfaces\Deletable;
17 use BookStack\Interfaces\Favouritable;
18 use BookStack\Interfaces\Loggable;
19 use BookStack\Interfaces\Sluggable;
20 use BookStack\Interfaces\Viewable;
22 use BookStack\Traits\HasCreatorAndUpdater;
23 use BookStack\Traits\HasOwner;
25 use Illuminate\Database\Eloquent\Builder;
26 use Illuminate\Database\Eloquent\Collection;
27 use Illuminate\Database\Eloquent\Relations\MorphMany;
28 use Illuminate\Database\Eloquent\SoftDeletes;
32 * The base class for book-like items such as pages, chapters & books.
33 * This is not a database model in itself but extended.
36 * @property string $name
37 * @property string $slug
38 * @property Carbon $created_at
39 * @property Carbon $updated_at
40 * @property Carbon $deleted_at
41 * @property int $created_by
42 * @property int $updated_by
43 * @property bool $restricted
44 * @property Collection $tags
46 * @method static Entity|Builder visible()
47 * @method static Builder withLastView()
48 * @method static Builder withViewCount()
50 abstract class Entity extends Model implements Sluggable, Favouritable, Viewable, Deletable, Loggable
53 use HasCreatorAndUpdater;
57 * @var string - Name of property where the main text content is found
59 public $textField = 'description';
62 * @var float - Multiplier for search indexing.
64 public $searchFactor = 1.0;
67 * Get the entities that are visible to the current user.
69 public function scopeVisible(Builder $query): Builder
71 return app()->make(PermissionApplicator::class)->restrictEntityQuery($query);
75 * Query scope to get the last view from the current user.
77 public function scopeWithLastView(Builder $query)
79 $viewedAtQuery = View::query()->select('updated_at')
80 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
81 ->where('viewable_type', '=', $this->getMorphClass())
82 ->where('user_id', '=', user()->id)
85 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
89 * Query scope to get the total view count of the entities.
91 public function scopeWithViewCount(Builder $query)
93 $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
94 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
95 ->where('viewable_type', '=', $this->getMorphClass())->take(1);
97 $query->addSelect(['view_count' => $viewCountQuery]);
101 * Compares this entity to another given entity.
102 * Matches by comparing class and id.
104 public function matches(self $entity): bool
106 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
110 * Checks if the current entity matches or contains the given.
112 public function matchesOrContains(self $entity): bool
114 if ($this->matches($entity)) {
118 if (($entity instanceof BookChild) && $this instanceof Book) {
119 return $entity->book_id === $this->id;
122 if ($entity instanceof Page && $this instanceof Chapter) {
123 return $entity->chapter_id === $this->id;
130 * Gets the activity objects for this entity.
132 public function activity(): MorphMany
134 return $this->morphMany(Activity::class, 'entity')
135 ->orderBy('created_at', 'desc');
139 * Get View objects for this entity.
141 public function views(): MorphMany
143 return $this->morphMany(View::class, 'viewable');
147 * Get the Tag models that have been user assigned to this entity.
149 public function tags(): MorphMany
151 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
155 * Get the comments for an entity.
157 public function comments(bool $orderByCreated = true): MorphMany
159 $query = $this->morphMany(Comment::class, 'entity');
161 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
165 * Get the related search terms.
167 public function searchTerms(): MorphMany
169 return $this->morphMany(SearchTerm::class, 'entity');
173 * Get this entities restrictions.
175 public function permissions(): MorphMany
177 return $this->morphMany(EntityPermission::class, 'restrictable');
181 * Check if this entity has a specific restriction set against it.
183 public function hasRestriction(int $role_id, string $action): bool
185 return $this->permissions()->where('role_id', '=', $role_id)
186 ->where('action', '=', $action)->count() > 0;
190 * Get the entity jointPermissions this is connected to.
192 public function jointPermissions(): MorphMany
194 return $this->morphMany(JointPermission::class, 'entity');
198 * Get the related delete records for this entity.
200 public function deletions(): MorphMany
202 return $this->morphMany(Deletion::class, 'deletable');
206 * Check if this instance or class is a certain type of entity.
207 * Examples of $type are 'page', 'book', 'chapter'.
209 * @deprecated Use instanceof instead.
211 public static function isA(string $type): bool
213 return static::getType() === strtolower($type);
217 * Get the entity type as a simple lowercase word.
219 public static function getType(): string
221 $className = array_slice(explode('\\', static::class), -1, 1)[0];
223 return strtolower($className);
227 * Gets a limited-length version of the entities name.
229 public function getShortName(int $length = 25): string
231 if (mb_strlen($this->name) <= $length) {
235 return mb_substr($this->name, 0, $length - 3) . '...';
239 * Get an excerpt of this entity's descriptive content to the specified length.
241 public function getExcerpt(int $length = 100): string
243 $text = $this->{$this->textField} ?? '';
245 if (mb_strlen($text) > $length) {
246 $text = mb_substr($text, 0, $length - 3) . '...';
253 * Get the url of this entity.
255 abstract public function getUrl(string $path = '/'): string;
258 * Get the parent entity if existing.
259 * This is the "static" parent and does not include dynamic
260 * relations such as shelves to books.
262 public function getParent(): ?self
264 if ($this instanceof Page) {
265 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
267 if ($this instanceof Chapter) {
268 return $this->book()->withTrashed()->first();
275 * Rebuild the permissions for this entity.
277 public function rebuildPermissions()
279 app()->make(JointPermissionBuilder::class)->rebuildForEntity(clone $this);
283 * Index the current entity for search.
285 public function indexForSearch()
287 app()->make(SearchIndex::class)->indexEntity(clone $this);
293 public function refreshSlug(): string
295 $this->slug = app()->make(SlugGenerator::class)->generate($this);
303 public function favourites(): MorphMany
305 return $this->morphMany(Favourite::class, 'favouritable');
309 * Check if the entity is a favourite of the current user.
311 public function isFavourite(): bool
313 return $this->favourites()
314 ->where('user_id', '=', user()->id)
321 public function logDescriptor(): string
323 return "({$this->id}) {$this->name}";