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 int $created_by
40 * @property int $updated_by
41 * @property bool $restricted
42 * @property Collection $tags
44 * @method static Entity|Builder visible()
45 * @method static Entity|Builder hasPermission(string $permission)
46 * @method static Builder withLastView()
47 * @method static Builder withViewCount()
49 abstract class Entity extends Model implements Sluggable, Favouritable, Viewable, Deletable, Loggable
52 use HasCreatorAndUpdater;
56 * @var string - Name of property where the main text content is found
58 public $textField = 'description';
61 * @var float - Multiplier for search indexing.
63 public $searchFactor = 1.0;
66 * Get the entities that are visible to the current user.
68 public function scopeVisible(Builder $query): Builder
70 return $this->scopeHasPermission($query, 'view');
74 * Scope the query to those entities that the current user has the given permission for.
76 public function scopeHasPermission(Builder $query, string $permission)
78 return Permissions::restrictEntityQuery($query, $permission);
82 * Query scope to get the last view from the current user.
84 public function scopeWithLastView(Builder $query)
86 $viewedAtQuery = View::query()->select('updated_at')
87 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
88 ->where('viewable_type', '=', $this->getMorphClass())
89 ->where('user_id', '=', user()->id)
92 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
96 * Query scope to get the total view count of the entities.
98 public function scopeWithViewCount(Builder $query)
100 $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
101 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
102 ->where('viewable_type', '=', $this->getMorphClass())->take(1);
104 $query->addSelect(['view_count' => $viewCountQuery]);
108 * Compares this entity to another given entity.
109 * Matches by comparing class and id.
111 public function matches(self $entity): bool
113 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
117 * Checks if the current entity matches or contains the given.
119 public function matchesOrContains(self $entity): bool
121 if ($this->matches($entity)) {
125 if (($entity instanceof BookChild) && $this instanceof Book) {
126 return $entity->book_id === $this->id;
129 if ($entity instanceof Page && $this instanceof Chapter) {
130 return $entity->chapter_id === $this->id;
137 * Gets the activity objects for this entity.
139 public function activity(): MorphMany
141 return $this->morphMany(Activity::class, 'entity')
142 ->orderBy('created_at', 'desc');
146 * Get View objects for this entity.
148 public function views(): MorphMany
150 return $this->morphMany(View::class, 'viewable');
154 * Get the Tag models that have been user assigned to this entity.
156 public function tags(): MorphMany
158 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
162 * Get the comments for an entity.
164 public function comments(bool $orderByCreated = true): MorphMany
166 $query = $this->morphMany(Comment::class, 'entity');
168 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
172 * Get the related search terms.
174 public function searchTerms(): MorphMany
176 return $this->morphMany(SearchTerm::class, 'entity');
180 * Get this entities restrictions.
182 public function permissions(): MorphMany
184 return $this->morphMany(EntityPermission::class, 'restrictable');
188 * Check if this entity has a specific restriction set against it.
190 public function hasRestriction(int $role_id, string $action): bool
192 return $this->permissions()->where('role_id', '=', $role_id)
193 ->where('action', '=', $action)->count() > 0;
197 * Get the entity jointPermissions this is connected to.
199 public function jointPermissions(): MorphMany
201 return $this->morphMany(JointPermission::class, 'entity');
205 * Get the related delete records for this entity.
207 public function deletions(): MorphMany
209 return $this->morphMany(Deletion::class, 'deletable');
213 * Check if this instance or class is a certain type of entity.
214 * Examples of $type are 'page', 'book', 'chapter'.
216 * @deprecated Use instanceof instead.
218 public static function isA(string $type): bool
220 return static::getType() === strtolower($type);
224 * Get the entity type as a simple lowercase word.
226 public static function getType(): string
228 $className = array_slice(explode('\\', static::class), -1, 1)[0];
230 return strtolower($className);
234 * Gets a limited-length version of the entities name.
236 public function getShortName(int $length = 25): string
238 if (mb_strlen($this->name) <= $length) {
242 return mb_substr($this->name, 0, $length - 3) . '...';
246 * Get an excerpt of this entity's descriptive content to the specified length.
248 public function getExcerpt(int $length = 100): string
250 $text = $this->{$this->textField} ?? '';
252 if (mb_strlen($text) > $length) {
253 $text = mb_substr($text, 0, $length - 3) . '...';
260 * Get the url of this entity.
262 abstract public function getUrl(string $path = '/'): string;
265 * Get the parent entity if existing.
266 * This is the "static" parent and does not include dynamic
267 * relations such as shelves to books.
269 public function getParent(): ?self
271 if ($this instanceof Page) {
272 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
274 if ($this instanceof Chapter) {
275 return $this->book()->withTrashed()->first();
282 * Rebuild the permissions for this entity.
284 public function rebuildPermissions()
286 /** @noinspection PhpUnhandledExceptionInspection */
287 Permissions::buildJointPermissionsForEntity(clone $this);
291 * Index the current entity for search.
293 public function indexForSearch()
295 app(SearchIndex::class)->indexEntity(clone $this);
301 public function refreshSlug(): string
303 $this->slug = app(SlugGenerator::class)->generate($this);
311 public function favourites(): MorphMany
313 return $this->morphMany(Favourite::class, 'favouritable');
317 * Check if the entity is a favourite of the current user.
319 public function isFavourite(): bool
321 return $this->favourites()
322 ->where('user_id', '=', user()->id)
329 public function logDescriptor(): string
331 return "({$this->id}) {$this->name}";