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 * Allows checking of the exact class, Used to check entity type.
205 * Cleaner method for is_a.
209 public static function isA($type)
211 return static::getType() === strtolower($type);
218 public static function getType()
220 return strtolower(static::getClassName());
224 * Get an instance of an entity of the given type.
228 public static function getEntityInstance($type)
230 $types = ['Page', 'Book', 'Chapter', 'Bookshelf'];
231 $className = str_replace([' ', '-', '_'], '', ucwords($type));
232 if (!in_array($className, $types)) {
236 return app('BookStack\\Entities\\' . $className);
240 * Gets a limited-length version of the entities name.
244 public function getShortName($length = 25)
246 if (mb_strlen($this->name) <= $length) {
249 return mb_substr($this->name, 0, $length - 3) . '...';
253 * Get the body text of this entity.
256 public function getText()
258 return $this->{$this->textField};
262 * Get an excerpt of this entity's descriptive content to the specified length.
266 public function getExcerpt(int $length = 100)
268 $text = $this->getText();
269 if (mb_strlen($text) > $length) {
270 $text = mb_substr($text, 0, $length-3) . '...';
276 * Get the url of this entity
280 public function getUrl($path = '/')
286 * Rebuild the permissions for this entity.
288 public function rebuildPermissions()
290 /** @noinspection PhpUnhandledExceptionInspection */
291 Permissions::buildJointPermissionsForEntity($this);
295 * Index the current entity for search
297 public function indexForSearch()
299 $searchService = app()->make(SearchService::class);
300 $searchService->indexEntity($this);
304 * Generate and set a new URL slug for this model.
306 public function refreshSlug(): string
308 $generator = new SlugGenerator($this);
309 $this->slug = $generator->generate();