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;
13 use BookStack\Traits\HasCreatorAndUpdater;
14 use BookStack\Traits\HasOwner;
16 use Illuminate\Database\Eloquent\Builder;
17 use Illuminate\Database\Eloquent\Collection;
18 use Illuminate\Database\Eloquent\Relations\MorphMany;
19 use Illuminate\Database\Eloquent\SoftDeletes;
23 * The base class for book-like items such as pages, chapters & books.
24 * This is not a database model in itself but extended.
27 * @property string $name
28 * @property string $slug
29 * @property Carbon $created_at
30 * @property Carbon $updated_at
31 * @property int $created_by
32 * @property int $updated_by
33 * @property boolean $restricted
34 * @property Collection $tags
35 * @method static Entity|Builder visible()
36 * @method static Entity|Builder hasPermission(string $permission)
37 * @method static Builder withLastView()
38 * @method static Builder withViewCount()
40 abstract class Entity extends Model
43 use HasCreatorAndUpdater;
47 * @var string - Name of property where the main text content is found
49 public $textField = 'description';
52 * @var float - Multiplier for search indexing.
54 public $searchFactor = 1.0;
57 * Get the entities that are visible to the current user.
59 public function scopeVisible(Builder $query): Builder
61 return $this->scopeHasPermission($query, 'view');
65 * Scope the query to those entities that the current user has the given permission for.
67 public function scopeHasPermission(Builder $query, string $permission)
69 return Permissions::restrictEntityQuery($query, $permission);
73 * Query scope to get the last view from the current user.
75 public function scopeWithLastView(Builder $query)
77 $viewedAtQuery = View::query()->select('updated_at')
78 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
79 ->where('viewable_type', '=', $this->getMorphClass())
80 ->where('user_id', '=', user()->id)
83 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
87 * Query scope to get the total view count of the entities.
89 public function scopeWithViewCount(Builder $query)
91 $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
92 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
93 ->where('viewable_type', '=', $this->getMorphClass())->take(1);
95 $query->addSelect(['view_count' => $viewCountQuery]);
99 * Compares this entity to another given entity.
100 * Matches by comparing class and id.
102 public function matches(Entity $entity): bool
104 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
108 * Checks if the current entity matches or contains the given.
110 public function matchesOrContains(Entity $entity): bool
112 if ($this->matches($entity)) {
116 if (($entity->isA('chapter') || $entity->isA('page')) && $this->isA('book')) {
117 return $entity->book_id === $this->id;
120 if ($entity->isA('page') && $this->isA('chapter')) {
121 return $entity->chapter_id === $this->id;
128 * Gets the activity objects for this entity.
130 public function activity(): MorphMany
132 return $this->morphMany(Activity::class, 'entity')
133 ->orderBy('created_at', 'desc');
137 * Get View objects for this entity.
139 public function views(): MorphMany
141 return $this->morphMany(View::class, 'viewable');
145 * Get the Tag models that have been user assigned to this entity.
147 public function tags(): MorphMany
149 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
153 * Get the comments for an entity
155 public function comments(bool $orderByCreated = true): MorphMany
157 $query = $this->morphMany(Comment::class, 'entity');
158 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
162 * Get the related search terms.
164 public function searchTerms(): MorphMany
166 return $this->morphMany(SearchTerm::class, 'entity');
170 * Get this entities restrictions.
172 public function permissions(): MorphMany
174 return $this->morphMany(EntityPermission::class, 'restrictable');
178 * Check if this entity has a specific restriction set against it.
180 public function hasRestriction(int $role_id, string $action): bool
182 return $this->permissions()->where('role_id', '=', $role_id)
183 ->where('action', '=', $action)->count() > 0;
187 * Get the entity jointPermissions this is connected to.
189 public function jointPermissions(): MorphMany
191 return $this->morphMany(JointPermission::class, 'entity');
195 * Get the related delete records for this entity.
197 public function deletions(): MorphMany
199 return $this->morphMany(Deletion::class, 'deletable');
203 * Check if this instance or class is a certain type of entity.
204 * Examples of $type are 'page', 'book', 'chapter'
206 public static function isA(string $type): bool
208 return static::getType() === strtolower($type);
212 * Get the entity type as a simple lowercase word.
214 public static function getType(): string
216 $className = array_slice(explode('\\', static::class), -1, 1)[0];
217 return strtolower($className);
221 * Gets a limited-length version of the entities name.
223 public function getShortName(int $length = 25): string
225 if (mb_strlen($this->name) <= $length) {
228 return mb_substr($this->name, 0, $length - 3) . '...';
232 * Get the body text of this entity.
234 public function getText(): string
236 return $this->{$this->textField} ?? '';
240 * Get an excerpt of this entity's descriptive content to the specified length.
242 public function getExcerpt(int $length = 100): string
244 $text = $this->getText();
246 if (mb_strlen($text) > $length) {
247 $text = mb_substr($text, 0, $length-3) . '...';
254 * Get the url of this entity
256 abstract public function getUrl(string $path = '/'): string;
259 * Get the parent entity if existing.
260 * This is the "static" parent and does not include dynamic
261 * relations such as shelves to books.
263 public function getParent(): ?Entity
265 if ($this->isA('page')) {
266 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
268 if ($this->isA('chapter')) {
269 return $this->book()->withTrashed()->first();
275 * Rebuild the permissions for this entity.
277 public function rebuildPermissions()
279 /** @noinspection PhpUnhandledExceptionInspection */
280 Permissions::buildJointPermissionsForEntity(clone $this);
284 * Index the current entity for search
286 public function indexForSearch()
288 app(SearchIndex::class)->indexEntity(clone $this);
292 * Generate and set a new URL slug for this model.
294 public function refreshSlug(): string
296 $this->slug = (new SlugGenerator)->generate($this);