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\Ownable;
14 use Illuminate\Database\Eloquent\Builder;
15 use Illuminate\Database\Eloquent\Collection;
16 use Illuminate\Database\Eloquent\Relations\MorphMany;
17 use Illuminate\Database\Eloquent\SoftDeletes;
21 * The base class for book-like items such as pages, chapters & books.
22 * This is not a database model in itself but extended.
25 * @property string $name
26 * @property string $slug
27 * @property Carbon $created_at
28 * @property Carbon $updated_at
29 * @property int $created_by
30 * @property int $updated_by
31 * @property boolean $restricted
32 * @property Collection $tags
33 * @method static Entity|Builder visible()
34 * @method static Entity|Builder hasPermission(string $permission)
35 * @method static Builder withLastView()
36 * @method static Builder withViewCount()
38 abstract class Entity extends Ownable
43 * @var string - Name of property where the main text content is found
45 public $textField = 'description';
48 * @var float - Multiplier for search indexing.
50 public $searchFactor = 1.0;
53 * Get the entities that are visible to the current user.
55 public function scopeVisible(Builder $query): Builder
57 return $this->scopeHasPermission($query, 'view');
61 * Scope the query to those entities that the current user has the given permission for.
63 public function scopeHasPermission(Builder $query, string $permission)
65 return Permissions::restrictEntityQuery($query, $permission);
69 * Query scope to get the last view from the current user.
71 public function scopeWithLastView(Builder $query)
73 $viewedAtQuery = View::query()->select('updated_at')
74 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
75 ->where('viewable_type', '=', $this->getMorphClass())
76 ->where('user_id', '=', user()->id)
79 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
83 * Query scope to get the total view count of the entities.
85 public function scopeWithViewCount(Builder $query)
87 $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
88 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
89 ->where('viewable_type', '=', $this->getMorphClass())->take(1);
91 $query->addSelect(['view_count' => $viewCountQuery]);
95 * Compares this entity to another given entity.
96 * Matches by comparing class and id.
98 public function matches(Entity $entity): bool
100 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
104 * Checks if the current entity matches or contains the given.
106 public function matchesOrContains(Entity $entity): bool
108 if ($this->matches($entity)) {
112 if (($entity->isA('chapter') || $entity->isA('page')) && $this->isA('book')) {
113 return $entity->book_id === $this->id;
116 if ($entity->isA('page') && $this->isA('chapter')) {
117 return $entity->chapter_id === $this->id;
124 * Gets the activity objects for this entity.
126 public function activity(): MorphMany
128 return $this->morphMany(Activity::class, 'entity')
129 ->orderBy('created_at', 'desc');
133 * Get View objects for this entity.
135 public function views(): MorphMany
137 return $this->morphMany(View::class, 'viewable');
141 * Get the Tag models that have been user assigned to this entity.
143 public function tags(): MorphMany
145 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
149 * Get the comments for an entity
151 public function comments(bool $orderByCreated = true): MorphMany
153 $query = $this->morphMany(Comment::class, 'entity');
154 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
158 * Get the related search terms.
160 public function searchTerms(): MorphMany
162 return $this->morphMany(SearchTerm::class, 'entity');
166 * Get this entities restrictions.
168 public function permissions(): MorphMany
170 return $this->morphMany(EntityPermission::class, 'restrictable');
174 * Check if this entity has a specific restriction set against it.
176 public function hasRestriction(int $role_id, string $action): bool
178 return $this->permissions()->where('role_id', '=', $role_id)
179 ->where('action', '=', $action)->count() > 0;
183 * Get the entity jointPermissions this is connected to.
185 public function jointPermissions(): MorphMany
187 return $this->morphMany(JointPermission::class, 'entity');
191 * Get the related delete records for this entity.
193 public function deletions(): MorphMany
195 return $this->morphMany(Deletion::class, 'deletable');
199 * Check if this instance or class is a certain type of entity.
200 * Examples of $type are 'page', 'book', 'chapter'
202 public static function isA(string $type): bool
204 return static::getType() === strtolower($type);
211 public static function getType()
213 return strtolower(static::getClassName());
217 * Gets a limited-length version of the entities name.
219 public function getShortName(int $length = 25): string
221 if (mb_strlen($this->name) <= $length) {
224 return mb_substr($this->name, 0, $length - 3) . '...';
228 * Get the body text of this entity.
230 public function getText(): string
232 return $this->{$this->textField} ?? '';
236 * Get an excerpt of this entity's descriptive content to the specified length.
238 public function getExcerpt(int $length = 100): string
240 $text = $this->getText();
242 if (mb_strlen($text) > $length) {
243 $text = mb_substr($text, 0, $length-3) . '...';
250 * Get the url of this entity
252 abstract public function getUrl(string $path = '/'): string;
255 * Get the parent entity if existing.
256 * This is the "static" parent and does not include dynamic
257 * relations such as shelves to books.
259 public function getParent(): ?Entity
261 if ($this->isA('page')) {
262 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
264 if ($this->isA('chapter')) {
265 return $this->book()->withTrashed()->first();
271 * Rebuild the permissions for this entity.
273 public function rebuildPermissions()
275 /** @noinspection PhpUnhandledExceptionInspection */
276 Permissions::buildJointPermissionsForEntity(clone $this);
280 * Index the current entity for search
282 public function indexForSearch()
284 app(SearchIndex::class)->indexEntity(clone $this);
288 * Generate and set a new URL slug for this model.
290 public function refreshSlug(): string
292 $this->slug = (new SlugGenerator)->generate($this);