1 <?php namespace BookStack\Entities\Models;
3 use BookStack\Actions\Activity;
4 use BookStack\Actions\Comment;
5 use BookStack\Actions\Favourite;
6 use BookStack\Actions\Tag;
7 use BookStack\Actions\View;
8 use BookStack\Auth\Permissions\EntityPermission;
9 use BookStack\Auth\Permissions\JointPermission;
10 use BookStack\Entities\Tools\SearchIndex;
11 use BookStack\Entities\Tools\SlugGenerator;
12 use BookStack\Facades\Permissions;
13 use BookStack\Interfaces\Favouritable;
14 use BookStack\Interfaces\Sluggable;
15 use BookStack\Interfaces\Viewable;
17 use BookStack\Traits\HasCreatorAndUpdater;
18 use BookStack\Traits\HasOwner;
20 use Illuminate\Database\Eloquent\Builder;
21 use Illuminate\Database\Eloquent\Collection;
22 use Illuminate\Database\Eloquent\Relations\MorphMany;
23 use Illuminate\Database\Eloquent\SoftDeletes;
27 * The base class for book-like items such as pages, chapters & books.
28 * This is not a database model in itself but extended.
31 * @property string $name
32 * @property string $slug
33 * @property Carbon $created_at
34 * @property Carbon $updated_at
35 * @property int $created_by
36 * @property int $updated_by
37 * @property boolean $restricted
38 * @property Collection $tags
39 * @method static Entity|Builder visible()
40 * @method static Entity|Builder hasPermission(string $permission)
41 * @method static Builder withLastView()
42 * @method static Builder withViewCount()
44 abstract class Entity extends Model implements Sluggable, Favouritable, Viewable
47 use HasCreatorAndUpdater;
51 * @var string - Name of property where the main text content is found
53 public $textField = 'description';
56 * @var float - Multiplier for search indexing.
58 public $searchFactor = 1.0;
61 * Get the entities that are visible to the current user.
63 public function scopeVisible(Builder $query): Builder
65 return $this->scopeHasPermission($query, 'view');
69 * Scope the query to those entities that the current user has the given permission for.
71 public function scopeHasPermission(Builder $query, string $permission)
73 return Permissions::restrictEntityQuery($query, $permission);
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(Entity $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(Entity $entity): bool
116 if ($this->matches($entity)) {
120 if (($entity->isA('chapter') || $entity->isA('page')) && $this->isA('book')) {
121 return $entity->book_id === $this->id;
124 if ($entity->isA('page') && $this->isA('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');
162 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
166 * Get the related search terms.
168 public function searchTerms(): MorphMany
170 return $this->morphMany(SearchTerm::class, 'entity');
174 * Get this entities restrictions.
176 public function permissions(): MorphMany
178 return $this->morphMany(EntityPermission::class, 'restrictable');
182 * Check if this entity has a specific restriction set against it.
184 public function hasRestriction(int $role_id, string $action): bool
186 return $this->permissions()->where('role_id', '=', $role_id)
187 ->where('action', '=', $action)->count() > 0;
191 * Get the entity jointPermissions this is connected to.
193 public function jointPermissions(): MorphMany
195 return $this->morphMany(JointPermission::class, 'entity');
199 * Get the related delete records for this entity.
201 public function deletions(): MorphMany
203 return $this->morphMany(Deletion::class, 'deletable');
207 * Check if this instance or class is a certain type of entity.
208 * Examples of $type are 'page', 'book', 'chapter'
210 public static function isA(string $type): bool
212 return static::getType() === strtolower($type);
216 * Get the entity type as a simple lowercase word.
218 public static function getType(): string
220 $className = array_slice(explode('\\', static::class), -1, 1)[0];
221 return strtolower($className);
225 * Gets a limited-length version of the entities name.
227 public function getShortName(int $length = 25): string
229 if (mb_strlen($this->name) <= $length) {
232 return mb_substr($this->name, 0, $length - 3) . '...';
236 * Get the body text of this entity.
238 public function getText(): string
240 return $this->{$this->textField} ?? '';
244 * Get an excerpt of this entity's descriptive content to the specified length.
246 public function getExcerpt(int $length = 100): string
248 $text = $this->getText();
250 if (mb_strlen($text) > $length) {
251 $text = mb_substr($text, 0, $length-3) . '...';
258 * Get the url of this entity
260 abstract public function getUrl(string $path = '/'): string;
263 * Get the parent entity if existing.
264 * This is the "static" parent and does not include dynamic
265 * relations such as shelves to books.
267 public function getParent(): ?Entity
269 if ($this->isA('page')) {
270 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
272 if ($this->isA('chapter')) {
273 return $this->book()->withTrashed()->first();
279 * Rebuild the permissions for this entity.
281 public function rebuildPermissions()
283 /** @noinspection PhpUnhandledExceptionInspection */
284 Permissions::buildJointPermissionsForEntity(clone $this);
288 * Index the current entity for search
290 public function indexForSearch()
292 app(SearchIndex::class)->indexEntity(clone $this);
298 public function refreshSlug(): string
300 $this->slug = app(SlugGenerator::class)->generate($this);
307 public function favourites(): MorphMany
309 return $this->morphMany(Favourite::class, 'favouritable');
313 * Check if the entity is a favourite of the current user.
315 public function isFavourite(): bool
317 return $this->favourites()
318 ->where('user_id', '=', user()->id)