1 <?php namespace BookStack\Entities;
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\Facades\Permissions;
10 use BookStack\Ownable;
12 use Illuminate\Database\Eloquent\Builder;
13 use Illuminate\Database\Eloquent\Collection;
14 use Illuminate\Database\Eloquent\Relations\MorphMany;
15 use Illuminate\Database\Eloquent\SoftDeletes;
19 * The base class for book-like items such as pages, chapters & books.
20 * This is not a database model in itself but extended.
23 * @property string $name
24 * @property string $slug
25 * @property Carbon $created_at
26 * @property Carbon $updated_at
27 * @property int $created_by
28 * @property int $updated_by
29 * @property boolean $restricted
30 * @property Collection $tags
31 * @method static Entity|Builder visible()
32 * @method static Entity|Builder hasPermission(string $permission)
33 * @method static Builder withLastView()
34 * @method static Builder withViewCount()
36 * @package BookStack\Entities
38 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)
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.
100 public function matches($entity)
102 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
106 * Checks if an entity matches or contains another given entity.
107 * @param Entity $entity
110 public function matchesOrContains(Entity $entity)
112 $matches = [get_class($this), $this->id] === [get_class($entity), $entity->id];
118 if (($entity->isA('chapter') || $entity->isA('page')) && $this->isA('book')) {
119 return $entity->book_id === $this->id;
122 if ($entity->isA('page') && $this->isA('chapter')) {
123 return $entity->chapter_id === $this->id;
130 * Gets the activity objects for this entity.
133 public function activity()
135 return $this->morphMany(Activity::class, 'entity')
136 ->orderBy('created_at', 'desc');
140 * Get View objects for this entity.
142 public function views()
144 return $this->morphMany(View::class, 'viewable');
148 * Get the Tag models that have been user assigned to this entity.
151 public function tags()
153 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
157 * Get the comments for an entity
158 * @param bool $orderByCreated
161 public function comments($orderByCreated = true)
163 $query = $this->morphMany(Comment::class, 'entity');
164 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
168 * Get the related search terms.
171 public function searchTerms()
173 return $this->morphMany(SearchTerm::class, 'entity');
177 * Get this entities restrictions.
179 public function permissions()
181 return $this->morphMany(EntityPermission::class, 'restrictable');
185 * Check if this entity has a specific restriction set against it.
190 public function hasRestriction($role_id, $action)
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 public static function isA(string $type): bool
218 return static::getType() === strtolower($type);
225 public static function getType()
227 return strtolower(static::getClassName());
231 * Get an instance of an entity of the given type.
235 public static function getEntityInstance($type)
237 $types = ['Page', 'Book', 'Chapter', 'Bookshelf'];
238 $className = str_replace([' ', '-', '_'], '', ucwords($type));
239 if (!in_array($className, $types)) {
243 return app('BookStack\\Entities\\' . $className);
247 * Gets a limited-length version of the entities name.
249 public function getShortName(int $length = 25): string
251 if (mb_strlen($this->name) <= $length) {
254 return mb_substr($this->name, 0, $length - 3) . '...';
258 * Get the body text of this entity.
261 public function getText()
263 return $this->{$this->textField};
267 * Get an excerpt of this entity's descriptive content to the specified length.
271 public function getExcerpt(int $length = 100)
273 $text = $this->getText();
274 if (mb_strlen($text) > $length) {
275 $text = mb_substr($text, 0, $length-3) . '...';
281 * Get the url of this entity
285 public function getUrl($path = '/')
291 * Get the parent entity if existing.
292 * This is the "static" parent and does not include dynamic
293 * relations such as shelves to books.
295 public function getParent(): ?Entity
297 if ($this->isA('page')) {
298 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
300 if ($this->isA('chapter')) {
301 return $this->book()->withTrashed()->first();
307 * Rebuild the permissions for this entity.
309 public function rebuildPermissions()
311 /** @noinspection PhpUnhandledExceptionInspection */
312 Permissions::buildJointPermissionsForEntity(clone $this);
316 * Index the current entity for search
318 public function indexForSearch()
320 $searchService = app()->make(SearchService::class);
321 $searchService->indexEntity(clone $this);
325 * Generate and set a new URL slug for this model.
327 public function refreshSlug(): string
329 $generator = new SlugGenerator($this);
330 $this->slug = $generator->generate();