3 namespace BookStack\Entities\Models;
5 use BookStack\Activity\Models\Activity;
6 use BookStack\Activity\Models\Comment;
7 use BookStack\Activity\Models\Favouritable;
8 use BookStack\Activity\Models\Favourite;
9 use BookStack\Activity\Models\Loggable;
10 use BookStack\Activity\Models\Tag;
11 use BookStack\Activity\Models\View;
12 use BookStack\Activity\Models\Viewable;
13 use BookStack\App\Model;
14 use BookStack\App\Sluggable;
15 use BookStack\Entities\Tools\SlugGenerator;
16 use BookStack\Permissions\JointPermissionBuilder;
17 use BookStack\Permissions\Models\EntityPermission;
18 use BookStack\Permissions\Models\JointPermission;
19 use BookStack\Permissions\PermissionApplicator;
20 use BookStack\References\Reference;
21 use BookStack\Search\SearchIndex;
22 use BookStack\Search\SearchTerm;
23 use BookStack\Users\Models\HasCreatorAndUpdater;
24 use BookStack\Users\Models\HasOwner;
26 use Illuminate\Database\Eloquent\Builder;
27 use Illuminate\Database\Eloquent\Collection;
28 use Illuminate\Database\Eloquent\Relations\MorphMany;
29 use Illuminate\Database\Eloquent\SoftDeletes;
33 * The base class for book-like items such as pages, chapters & books.
34 * This is not a database model in itself but extended.
37 * @property string $name
38 * @property string $slug
39 * @property Carbon $created_at
40 * @property Carbon $updated_at
41 * @property Carbon $deleted_at
42 * @property int $created_by
43 * @property int $updated_by
44 * @property Collection $tags
46 * @method static Entity|Builder visible()
47 * @method static Builder withLastView()
48 * @method static Builder withViewCount()
50 abstract class Entity extends Model implements Sluggable, Favouritable, Viewable, Deletable, Loggable
53 use HasCreatorAndUpdater;
57 * @var string - Name of property where the main text content is found
59 public $textField = 'description';
62 * @var float - Multiplier for search indexing.
64 public $searchFactor = 1.0;
67 * Get the entities that are visible to the current user.
69 public function scopeVisible(Builder $query): Builder
71 return app()->make(PermissionApplicator::class)->restrictEntityQuery($query);
75 * Query scope to get the last view from the current user.
77 public function scopeWithLastView(Builder $query)
79 $viewedAtQuery = View::query()->select('updated_at')
80 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
81 ->where('viewable_type', '=', $this->getMorphClass())
82 ->where('user_id', '=', user()->id)
85 return $query->addSelect(['last_viewed_at' => $viewedAtQuery]);
89 * Query scope to get the total view count of the entities.
91 public function scopeWithViewCount(Builder $query)
93 $viewCountQuery = View::query()->selectRaw('SUM(views) as view_count')
94 ->whereColumn('viewable_id', '=', $this->getTable() . '.id')
95 ->where('viewable_type', '=', $this->getMorphClass())->take(1);
97 $query->addSelect(['view_count' => $viewCountQuery]);
101 * Compares this entity to another given entity.
102 * Matches by comparing class and id.
104 public function matches(self $entity): bool
106 return [get_class($this), $this->id] === [get_class($entity), $entity->id];
110 * Checks if the current entity matches or contains the given.
112 public function matchesOrContains(self $entity): bool
114 if ($this->matches($entity)) {
118 if (($entity instanceof BookChild) && $this instanceof Book) {
119 return $entity->book_id === $this->id;
122 if ($entity instanceof Page && $this instanceof Chapter) {
123 return $entity->chapter_id === $this->id;
130 * Gets the activity objects for this entity.
132 public function activity(): MorphMany
134 return $this->morphMany(Activity::class, 'entity')
135 ->orderBy('created_at', 'desc');
139 * Get View objects for this entity.
141 public function views(): MorphMany
143 return $this->morphMany(View::class, 'viewable');
147 * Get the Tag models that have been user assigned to this entity.
149 public function tags(): MorphMany
151 return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
155 * Get the comments for an entity.
157 public function comments(bool $orderByCreated = true): MorphMany
159 $query = $this->morphMany(Comment::class, 'entity');
161 return $orderByCreated ? $query->orderBy('created_at', 'asc') : $query;
165 * Get the related search terms.
167 public function searchTerms(): MorphMany
169 return $this->morphMany(SearchTerm::class, 'entity');
173 * Get this entities restrictions.
175 public function permissions(): MorphMany
177 return $this->morphMany(EntityPermission::class, 'entity');
181 * Check if this entity has a specific restriction set against it.
183 public function hasPermissions(): bool
185 return $this->permissions()->count() > 0;
189 * Get the entity jointPermissions this is connected to.
191 public function jointPermissions(): MorphMany
193 return $this->morphMany(JointPermission::class, 'entity');
197 * Get the related delete records for this entity.
199 public function deletions(): MorphMany
201 return $this->morphMany(Deletion::class, 'deletable');
205 * Get the references pointing from this entity to other items.
207 public function referencesFrom(): MorphMany
209 return $this->morphMany(Reference::class, 'from');
213 * Get the references pointing to this entity from other items.
215 public function referencesTo(): MorphMany
217 return $this->morphMany(Reference::class, 'to');
221 * Check if this instance or class is a certain type of entity.
222 * Examples of $type are 'page', 'book', 'chapter'.
224 * @deprecated Use instanceof instead.
226 public static function isA(string $type): bool
228 return static::getType() === strtolower($type);
232 * Get the entity type as a simple lowercase word.
234 public static function getType(): string
236 $className = array_slice(explode('\\', static::class), -1, 1)[0];
238 return strtolower($className);
242 * Gets a limited-length version of the entities name.
244 public function getShortName(int $length = 25): string
246 if (mb_strlen($this->name) <= $length) {
250 return mb_substr($this->name, 0, $length - 3) . '...';
254 * Get an excerpt of this entity's descriptive content to the specified length.
256 public function getExcerpt(int $length = 100): string
258 $text = $this->{$this->textField} ?? '';
260 if (mb_strlen($text) > $length) {
261 $text = mb_substr($text, 0, $length - 3) . '...';
268 * Get the url of this entity.
270 abstract public function getUrl(string $path = '/'): string;
273 * Get the parent entity if existing.
274 * This is the "static" parent and does not include dynamic
275 * relations such as shelves to books.
277 public function getParent(): ?self
279 if ($this instanceof Page) {
280 return $this->chapter_id ? $this->chapter()->withTrashed()->first() : $this->book()->withTrashed()->first();
282 if ($this instanceof Chapter) {
283 return $this->book()->withTrashed()->first();
290 * Rebuild the permissions for this entity.
292 public function rebuildPermissions()
294 app()->make(JointPermissionBuilder::class)->rebuildForEntity(clone $this);
298 * Index the current entity for search.
300 public function indexForSearch()
302 app()->make(SearchIndex::class)->indexEntity(clone $this);
308 public function refreshSlug(): string
310 $this->slug = app()->make(SlugGenerator::class)->generate($this);
318 public function favourites(): MorphMany
320 return $this->morphMany(Favourite::class, 'favouritable');
324 * Check if the entity is a favourite of the current user.
326 public function isFavourite(): bool
328 return $this->favourites()
329 ->where('user_id', '=', user()->id)
336 public function logDescriptor(): string
338 return "({$this->id}) {$this->name}";