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\Entities\Tools\SearchIndex;
13 use BookStack\Entities\Tools\SlugGenerator;
14 use BookStack\Facades\Permissions;
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\Traits\HasCreatorAndUpdater;
22 use BookStack\Traits\HasOwner;
24 use Illuminate\Database\Eloquent\Builder;
25 use Illuminate\Database\Eloquent\Collection;
26 use Illuminate\Database\Eloquent\Relations\MorphMany;
27 use Illuminate\Database\Eloquent\SoftDeletes;
31 * The base class for book-like items such as pages, chapters & books.
32 * This is not a database model in itself but extended.
35 * @property string $name
36 * @property string $slug
37 * @property Carbon $created_at
38 * @property Carbon $updated_at
39 * @property Carbon $deleted_at
40 * @property int $created_by
41 * @property int $updated_by
42 * @property bool $restricted
43 * @property Collection $tags
45 * @method static Entity|Builder visible()
46 * @method static Entity|Builder hasPermission(string $permission)
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 $this->scopeHasPermission($query, 'view');
75 * Scope the query to those entities that the current user has the given permission for.
77 public function scopeHasPermission(Builder $query, string $permission)
79 return Permissions::restrictEntityQuery($query, $permission);
83 * Query scope to get the last view from the current user.
85 public function scopeWithLastView(Builder $query)
87 $viewedAtQuery = View::query()->select('updated_at')
88 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
89 ->where('viewable_type', '=', $this->getMorphClass())
90 ->where('user_id', '=', user()->id)
93 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
97 * Query scope to get the total view count of the entities.
99 public function scopeWithViewCount(Builder $query)
101 $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
102 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
103 ->where('viewable_type', '=', $this->getMorphClass())->take(1);
105 $query->addSelect(['view_count' => $viewCountQuery]);
109 * Compares this entity to another given entity.
110 * Matches by comparing class and id.
112 public function matches(self $entity): bool
114 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
118 * Checks if the current entity matches or contains the given.
120 public function matchesOrContains(self $entity): bool
122 if ($this->matches($entity)) {
126 if (($entity instanceof BookChild) && $this instanceof Book) {
127 return $entity->book_id === $this->id;
130 if ($entity instanceof Page && $this instanceof Chapter) {
131 return $entity->chapter_id === $this->id;
138 * Gets the activity objects for this entity.
140 public function activity(): MorphMany
142 return $this->morphMany(Activity::class, 'entity')
143 ->orderBy('created_at', 'desc');
147 * Get View objects for this entity.
149 public function views(): MorphMany
151 return $this->morphMany(View::class, 'viewable');
155 * Get the Tag models that have been user assigned to this entity.
157 public function tags(): MorphMany
159 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
163 * Get the comments for an entity.
165 public function comments(bool $orderByCreated = true): MorphMany
167 $query = $this->morphMany(Comment::class, 'entity');
169 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
173 * Get the related search terms.
175 public function searchTerms(): MorphMany
177 return $this->morphMany(SearchTerm::class, 'entity');
181 * Get this entities restrictions.
183 public function permissions(): MorphMany
185 return $this->morphMany(EntityPermission::class, 'restrictable');
189 * Check if this entity has a specific restriction set against it.
191 public function hasRestriction(int $role_id, string $action): bool
193 return $this->permissions()->where('role_id', '=', $role_id)
194 ->where('action', '=', $action)->count() > 0;
198 * Get the entity jointPermissions this is connected to.
200 public function jointPermissions(): MorphMany
202 return $this->morphMany(JointPermission::class, 'entity');
206 * Get the related delete records for this entity.
208 public function deletions(): MorphMany
210 return $this->morphMany(Deletion::class, 'deletable');
214 * Check if this instance or class is a certain type of entity.
215 * Examples of $type are 'page', 'book', 'chapter'.
217 * @deprecated Use instanceof instead.
219 public static function isA(string $type): bool
221 return static::getType() === strtolower($type);
225 * Get the entity type as a simple lowercase word.
227 public static function getType(): string
229 $className = array_slice(explode('\\', static::class), -1, 1)[0];
231 return strtolower($className);
235 * Gets a limited-length version of the entities name.
237 public function getShortName(int $length = 25): string
239 if (mb_strlen($this->name) <= $length) {
243 return mb_substr($this->name, 0, $length - 3) . '...';
247 * Get an excerpt of this entity's descriptive content to the specified length.
249 public function getExcerpt(int $length = 100): string
251 $text = $this->{$this->textField} ?? '';
253 if (mb_strlen($text) > $length) {
254 $text = mb_substr($text, 0, $length - 3) . '...';
261 * Get the url of this entity.
263 abstract public function getUrl(string $path = '/'): string;
266 * Get the parent entity if existing.
267 * This is the "static" parent and does not include dynamic
268 * relations such as shelves to books.
270 public function getParent(): ?self
272 if ($this instanceof Page) {
273 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
275 if ($this instanceof Chapter) {
276 return $this->book()->withTrashed()->first();
283 * Rebuild the permissions for this entity.
285 public function rebuildPermissions()
287 /** @noinspection PhpUnhandledExceptionInspection */
288 Permissions::buildJointPermissionsForEntity(clone $this);
292 * Index the current entity for search.
294 public function indexForSearch()
296 app(SearchIndex::class)->indexEntity(clone $this);
302 public function refreshSlug(): string
304 $this->slug = app(SlugGenerator::class)->generate($this);
312 public function favourites(): MorphMany
314 return $this->morphMany(Favourite::class, 'favouritable');
318 * Check if the entity is a favourite of the current user.
320 public function isFavourite(): bool
322 return $this->favourites()
323 ->where('user_id', '=', user()->id)
330 public function logDescriptor(): string
332 return "({$this->id}) {$this->name}";