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;
18 * The base class for book-like items such as pages, chapters & books.
19 * This is not a database model in itself but extended.
22 * @property string $name
23 * @property string $slug
24 * @property Carbon $created_at
25 * @property Carbon $updated_at
26 * @property int $created_by
27 * @property int $updated_by
28 * @property boolean $restricted
29 * @property Collection $tags
30 * @method static Entity|Builder visible()
31 * @method static Entity|Builder hasPermission(string $permission)
32 * @method static Builder withLastView()
33 * @method static Builder withViewCount()
35 * @package BookStack\Entities
37 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.
198 public function jointPermissions()
200 return $this->morphMany(JointPermission::class, 'entity');
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);
216 public static function getType()
218 return strtolower(static::getClassName());
222 * Get an instance of an entity of the given type.
226 public static function getEntityInstance($type)
228 $types = ['Page', 'Book', 'Chapter', 'Bookshelf'];
229 $className = str_replace([' ', '-', '_'], '', ucwords($type));
230 if (!in_array($className, $types)) {
234 return app('BookStack\\Entities\\' . $className);
238 * Gets a limited-length version of the entities name.
240 public function getShortName(int $length = 25): string
242 if (mb_strlen($this->name) <= $length) {
245 return mb_substr($this->name, 0, $length - 3) . '...';
249 * Get the body text of this entity.
252 public function getText()
254 return $this->{$this->textField};
258 * Get an excerpt of this entity's descriptive content to the specified length.
262 public function getExcerpt(int $length = 100)
264 $text = $this->getText();
265 if (mb_strlen($text) > $length) {
266 $text = mb_substr($text, 0, $length-3) . '...';
272 * Get the url of this entity
276 public function getUrl($path = '/')
282 * Rebuild the permissions for this entity.
284 public function rebuildPermissions()
286 /** @noinspection PhpUnhandledExceptionInspection */
287 Permissions::buildJointPermissionsForEntity(clone $this);
291 * Index the current entity for search
293 public function indexForSearch()
295 $searchService = app()->make(SearchService::class);
296 $searchService->indexEntity(clone $this);
300 * Generate and set a new URL slug for this model.
302 public function refreshSlug(): string
304 $generator = new SlugGenerator($this);
305 $this->slug = $generator->generate();