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 class Entity extends Ownable
41 * @var string - Name of property where the main text content is found
43 public $textField = 'description';
46 * @var float - Multiplier for search indexing.
48 public $searchFactor = 1.0;
51 * Get the entities that are visible to the current user.
53 public function scopeVisible(Builder $query)
55 return $this->scopeHasPermission($query, 'view');
59 * Scope the query to those entities that the current user has the given permission for.
61 public function scopeHasPermission(Builder $query, string $permission)
63 return Permissions::restrictEntityQuery($query, $permission);
67 * Query scope to get the last view from the current user.
69 public function scopeWithLastView(Builder $query)
71 $viewedAtQuery = View::query()->select('updated_at')
72 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
73 ->where('viewable_type', '=', $this->getMorphClass())
74 ->where('user_id', '=', user()->id)
77 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
81 * Query scope to get the total view count of the entities.
83 public function scopeWithViewCount(Builder $query)
85 $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
86 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
87 ->where('viewable_type', '=', $this->getMorphClass())->take(1);
89 $query->addSelect(['view_count' => $viewCountQuery]);
93 * Compares this entity to another given entity.
94 * Matches by comparing class and id.
98 public function matches($entity)
100 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
104 * Checks if an entity matches or contains another given entity.
105 * @param Entity $entity
108 public function matchesOrContains(Entity $entity)
110 $matches = [get_class($this), $this->id] === [get_class($entity), $entity->id];
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.
131 public function activity()
133 return $this->morphMany(Activity::class, 'entity')
134 ->orderBy('created_at', 'desc');
138 * Get View objects for this entity.
140 public function views()
142 return $this->morphMany(View::class, 'viewable');
146 * Get the Tag models that have been user assigned to this entity.
149 public function tags()
151 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
155 * Get the comments for an entity
156 * @param bool $orderByCreated
159 public function comments($orderByCreated = true)
161 $query = $this->morphMany(Comment::class, 'entity');
162 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
166 * Get the related search terms.
169 public function searchTerms()
171 return $this->morphMany(SearchTerm::class, 'entity');
175 * Get this entities restrictions.
177 public function permissions()
179 return $this->morphMany(EntityPermission::class, 'restrictable');
183 * Check if this entity has a specific restriction set against it.
188 public function hasRestriction($role_id, $action)
190 return $this->permissions()->where('role_id', '=', $role_id)
191 ->where('action', '=', $action)->count() > 0;
195 * Get the entity jointPermissions this is connected to.
197 public function jointPermissions(): MorphMany
199 return $this->morphMany(JointPermission::class, 'entity');
203 * Get the related delete records for this entity.
205 public function deletions(): MorphMany
207 return $this->morphMany(Deletion::class, 'deletable');
211 * Check if this instance or class is a certain type of entity.
212 * Examples of $type are 'page', 'book', 'chapter'
214 public static function isA(string $type): bool
216 return static::getType() === strtolower($type);
223 public static function getType()
225 return strtolower(static::getClassName());
229 * Get an instance of an entity of the given type.
233 public static function getEntityInstance($type)
235 $types = ['Page', 'Book', 'Chapter', 'Bookshelf'];
236 $className = str_replace([' ', '-', '_'], '', ucwords($type));
237 if (!in_array($className, $types)) {
241 return app('BookStack\\Entities\\' . $className);
245 * Gets a limited-length version of the entities name.
247 public function getShortName(int $length = 25): string
249 if (mb_strlen($this->name) <= $length) {
252 return mb_substr($this->name, 0, $length - 3) . '...';
256 * Get the body text of this entity.
259 public function getText()
261 return $this->{$this->textField};
265 * Get an excerpt of this entity's descriptive content to the specified length.
269 public function getExcerpt(int $length = 100)
271 $text = $this->getText();
272 if (mb_strlen($text) > $length) {
273 $text = mb_substr($text, 0, $length-3) . '...';
279 * Get the url of this entity
283 public function getUrl($path = '/')
289 * Get the parent entity if existing.
290 * This is the "static" parent and does not include dynamic
291 * relations such as shelves to books.
293 public function getParent(): ?Entity
295 if ($this->isA('page')) {
296 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
298 if ($this->isA('chapter')) {
299 return $this->book()->withTrashed()->first();
305 * Rebuild the permissions for this entity.
307 public function rebuildPermissions()
309 /** @noinspection PhpUnhandledExceptionInspection */
310 Permissions::buildJointPermissionsForEntity(clone $this);
314 * Index the current entity for search
316 public function indexForSearch()
318 $searchService = app()->make(SearchService::class);
319 $searchService->indexEntity(clone $this);
323 * Generate and set a new URL slug for this model.
325 public function refreshSlug(): string
327 $this->slug = (new SlugGenerator)->generate($this);