1 <?php namespace BookStack\Entities\Models;
3 use BookStack\Actions\Activity;
4 use BookStack\Actions\Comment;
5 use BookStack\Actions\Tag;
6 use BookStack\Actions\View;
7 use BookStack\Auth\Permissions\EntityPermission;
8 use BookStack\Auth\Permissions\JointPermission;
9 use BookStack\Entities\Tools\SearchIndex;
10 use BookStack\Entities\Tools\SlugGenerator;
11 use BookStack\Facades\Permissions;
12 use BookStack\Interfaces\Sluggable;
14 use BookStack\Traits\HasCreatorAndUpdater;
15 use BookStack\Traits\HasOwner;
17 use Illuminate\Database\Eloquent\Builder;
18 use Illuminate\Database\Eloquent\Collection;
19 use Illuminate\Database\Eloquent\Relations\MorphMany;
20 use Illuminate\Database\Eloquent\SoftDeletes;
24 * The base class for book-like items such as pages, chapters & books.
25 * This is not a database model in itself but extended.
28 * @property string $name
29 * @property string $slug
30 * @property Carbon $created_at
31 * @property Carbon $updated_at
32 * @property int $created_by
33 * @property int $updated_by
34 * @property boolean $restricted
35 * @property Collection $tags
36 * @method static Entity|Builder visible()
37 * @method static Entity|Builder hasPermission(string $permission)
38 * @method static Builder withLastView()
39 * @method static Builder withViewCount()
41 abstract class Entity extends Model implements Sluggable
44 use HasCreatorAndUpdater;
48 * @var string - Name of property where the main text content is found
50 public $textField = 'description';
53 * @var float - Multiplier for search indexing.
55 public $searchFactor = 1.0;
58 * Get the entities that are visible to the current user.
60 public function scopeVisible(Builder $query): Builder
62 return $this->scopeHasPermission($query, 'view');
66 * Scope the query to those entities that the current user has the given permission for.
68 public function scopeHasPermission(Builder $query, string $permission)
70 return Permissions::restrictEntityQuery($query, $permission);
74 * Query scope to get the last view from the current user.
76 public function scopeWithLastView(Builder $query)
78 $viewedAtQuery = View::query()->select('updated_at')
79 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
80 ->where('viewable_type', '=', $this->getMorphClass())
81 ->where('user_id', '=', user()->id)
84 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
88 * Query scope to get the total view count of the entities.
90 public function scopeWithViewCount(Builder $query)
92 $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
93 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
94 ->where('viewable_type', '=', $this->getMorphClass())->take(1);
96 $query->addSelect(['view_count' => $viewCountQuery]);
100 * Compares this entity to another given entity.
101 * Matches by comparing class and id.
103 public function matches(Entity $entity): bool
105 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
109 * Checks if the current entity matches or contains the given.
111 public function matchesOrContains(Entity $entity): bool
113 if ($this->matches($entity)) {
117 if (($entity->isA('chapter') || $entity->isA('page')) && $this->isA('book')) {
118 return $entity->book_id === $this->id;
121 if ($entity->isA('page') && $this->isA('chapter')) {
122 return $entity->chapter_id === $this->id;
129 * Gets the activity objects for this entity.
131 public function activity(): MorphMany
133 return $this->morphMany(Activity::class, 'entity')
134 ->orderBy('created_at', 'desc');
138 * Get View objects for this entity.
140 public function views(): MorphMany
142 return $this->morphMany(View::class, 'viewable');
146 * Get the Tag models that have been user assigned to this entity.
148 public function tags(): MorphMany
150 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
154 * Get the comments for an entity
156 public function comments(bool $orderByCreated = true): MorphMany
158 $query = $this->morphMany(Comment::class, 'entity');
159 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
163 * Get the related search terms.
165 public function searchTerms(): MorphMany
167 return $this->morphMany(SearchTerm::class, 'entity');
171 * Get this entities restrictions.
173 public function permissions(): MorphMany
175 return $this->morphMany(EntityPermission::class, 'restrictable');
179 * Check if this entity has a specific restriction set against it.
181 public function hasRestriction(int $role_id, string $action): bool
183 return $this->permissions()->where('role_id', '=', $role_id)
184 ->where('action', '=', $action)->count() > 0;
188 * Get the entity jointPermissions this is connected to.
190 public function jointPermissions(): MorphMany
192 return $this->morphMany(JointPermission::class, 'entity');
196 * Get the related delete records for this entity.
198 public function deletions(): MorphMany
200 return $this->morphMany(Deletion::class, 'deletable');
204 * Check if this instance or class is a certain type of entity.
205 * Examples of $type are 'page', 'book', 'chapter'
207 public static function isA(string $type): bool
209 return static::getType() === strtolower($type);
213 * Get the entity type as a simple lowercase word.
215 public static function getType(): string
217 $className = array_slice(explode('\\', static::class), -1, 1)[0];
218 return strtolower($className);
222 * Gets a limited-length version of the entities name.
224 public function getShortName(int $length = 25): string
226 if (mb_strlen($this->name) <= $length) {
229 return mb_substr($this->name, 0, $length - 3) . '...';
233 * Get the body text of this entity.
235 public function getText(): string
237 return $this->{$this->textField} ?? '';
241 * Get an excerpt of this entity's descriptive content to the specified length.
243 public function getExcerpt(int $length = 100): string
245 $text = $this->getText();
247 if (mb_strlen($text) > $length) {
248 $text = mb_substr($text, 0, $length-3) . '...';
255 * Get the url of this entity
257 abstract public function getUrl(string $path = '/'): string;
260 * Get the parent entity if existing.
261 * This is the "static" parent and does not include dynamic
262 * relations such as shelves to books.
264 public function getParent(): ?Entity
266 if ($this->isA('page')) {
267 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
269 if ($this->isA('chapter')) {
270 return $this->book()->withTrashed()->first();
276 * Rebuild the permissions for this entity.
278 public function rebuildPermissions()
280 /** @noinspection PhpUnhandledExceptionInspection */
281 Permissions::buildJointPermissionsForEntity(clone $this);
285 * Index the current entity for search
287 public function indexForSearch()
289 app(SearchIndex::class)->indexEntity(clone $this);
295 public function refreshSlug(): string
297 $this->slug = app(SlugGenerator::class)->generate($this);