]> BookStack Code Mirror - bookstack/blob - app/Users/Models/User.php
Slugs: Added slug recording at points of generation
[bookstack] / app / Users / Models / User.php
1 <?php
2
3 namespace BookStack\Users\Models;
4
5 use BookStack\Access\Mfa\MfaValue;
6 use BookStack\Access\Notifications\ResetPasswordNotification;
7 use BookStack\Access\SocialAccount;
8 use BookStack\Activity\Models\Favourite;
9 use BookStack\Activity\Models\Loggable;
10 use BookStack\Activity\Models\Watch;
11 use BookStack\Api\ApiToken;
12 use BookStack\App\Model;
13 use BookStack\App\SluggableInterface;
14 use BookStack\Permissions\Permission;
15 use BookStack\Translation\LocaleDefinition;
16 use BookStack\Translation\LocaleManager;
17 use BookStack\Uploads\Image;
18 use Carbon\Carbon;
19 use Exception;
20 use Illuminate\Auth\Authenticatable;
21 use Illuminate\Auth\Passwords\CanResetPassword;
22 use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
23 use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
24 use Illuminate\Database\Eloquent\Builder;
25 use Illuminate\Database\Eloquent\Factories\HasFactory;
26 use Illuminate\Database\Eloquent\Relations\BelongsTo;
27 use Illuminate\Database\Eloquent\Relations\BelongsToMany;
28 use Illuminate\Database\Eloquent\Relations\HasMany;
29 use Illuminate\Notifications\Notifiable;
30 use Illuminate\Support\Collection;
31
32 /**
33  * @property int        $id
34  * @property string     $name
35  * @property string     $slug
36  * @property string     $email
37  * @property string     $password
38  * @property Carbon     $created_at
39  * @property Carbon     $updated_at
40  * @property bool       $email_confirmed
41  * @property int        $image_id
42  * @property string     $external_auth_id
43  * @property string     $system_name
44  * @property Collection $roles
45  * @property Collection $mfaValues
46  * @property ?Image     $avatar
47  */
48 class User extends Model implements AuthenticatableContract, CanResetPasswordContract, Loggable, SluggableInterface
49 {
50     use HasFactory;
51     use Authenticatable;
52     use CanResetPassword;
53     use Notifiable;
54
55     /**
56      * The database table used by the model.
57      *
58      * @var string
59      */
60     protected $table = 'users';
61
62     /**
63      * The attributes that are mass assignable.
64      *
65      * @var list<string>
66      */
67     protected $fillable = ['name', 'email'];
68
69     protected $casts = ['last_activity_at' => 'datetime'];
70
71     /**
72      * The attributes excluded from the model's JSON form.
73      *
74      * @var list<string>
75      */
76     protected $hidden = [
77         'password', 'remember_token', 'system_name', 'email_confirmed', 'external_auth_id', 'email',
78         'created_at', 'updated_at', 'image_id', 'roles', 'avatar', 'user_id', 'pivot',
79     ];
80
81     /**
82      * This holds the user's permissions when loaded.
83      */
84     protected ?Collection $permissions;
85
86     /**
87      * This holds the user's avatar URL when loaded to prevent re-calculating within the same request.
88      */
89     protected string $avatarUrl = '';
90
91     /**
92      * Returns the default public user.
93      * Fetches from the container as a singleton to effectively cache at an app level.
94      */
95     public static function getGuest(): self
96     {
97         return app()->make('users.default');
98     }
99
100     /**
101      * Check if the user is the default public user.
102      */
103     public function isGuest(): bool
104     {
105         return $this->system_name === 'public';
106     }
107
108     /**
109      * Check if the user has general access to the application.
110      */
111     public function hasAppAccess(): bool
112     {
113         return !$this->isGuest() || setting('app-public');
114     }
115
116     /**
117      * The roles that belong to the user.
118      *
119      * @return BelongsToMany<Role, $this>
120      */
121     public function roles(): BelongsToMany
122     {
123         return $this->belongsToMany(Role::class);
124     }
125
126     /**
127      * Check if the user has a role.
128      */
129     public function hasRole($roleId): bool
130     {
131         return $this->roles->pluck('id')->contains($roleId);
132     }
133
134     /**
135      * Check if the user has a role.
136      */
137     public function hasSystemRole(string $roleSystemName): bool
138     {
139         return $this->roles->pluck('system_name')->contains($roleSystemName);
140     }
141
142     /**
143      * Attach the default system role to this user.
144      */
145     public function attachDefaultRole(): void
146     {
147         $roleId = intval(setting('registration-role'));
148         if ($roleId && $this->roles()->where('id', '=', $roleId)->count() === 0) {
149             $this->roles()->attach($roleId);
150         }
151     }
152
153     /**
154      * Check if the user has a particular permission.
155      */
156     public function can(string|Permission $permission): bool
157     {
158         $permissionName = is_string($permission) ? $permission : $permission->value;
159         return $this->permissions()->contains($permissionName);
160     }
161
162     /**
163      * Get all permissions belonging to the current user.
164      */
165     protected function permissions(): Collection
166     {
167         if (isset($this->permissions)) {
168             return $this->permissions;
169         }
170
171         $this->permissions = $this->newQuery()->getConnection()->table('role_user', 'ru')
172             ->select('role_permissions.name as name')->distinct()
173             ->leftJoin('permission_role', 'ru.role_id', '=', 'permission_role.role_id')
174             ->leftJoin('role_permissions', 'permission_role.permission_id', '=', 'role_permissions.id')
175             ->where('ru.user_id', '=', $this->id)
176             ->pluck('name');
177
178         return $this->permissions;
179     }
180
181     /**
182      * Clear any cached permissions in this instance.
183      */
184     public function clearPermissionCache(): void
185     {
186         $this->permissions = null;
187     }
188
189     /**
190      * Attach a role to this user.
191      */
192     public function attachRole(Role $role): void
193     {
194         $this->roles()->attach($role->id);
195         $this->unsetRelation('roles');
196     }
197
198     /**
199      * Get the social account associated with this user.
200      */
201     public function socialAccounts(): HasMany
202     {
203         return $this->hasMany(SocialAccount::class);
204     }
205
206     /**
207      * Check if the user has a social account,
208      * If a driver is passed, it checks for that single account type.
209      */
210     public function hasSocialAccount(string $socialDriver = ''): bool
211     {
212         if (empty($socialDriver)) {
213             return $this->socialAccounts()->count() > 0;
214         }
215
216         return $this->socialAccounts()->where('driver', '=', $socialDriver)->exists();
217     }
218
219     /**
220      * Returns a URL to the user's avatar.
221      */
222     public function getAvatar(int $size = 50): string
223     {
224         $default = url('/user_avatar.png');
225         $imageId = $this->image_id;
226         if ($imageId === 0 || $imageId === '0' || $imageId === null) {
227             return $default;
228         }
229
230         if (!empty($this->avatarUrl)) {
231             return $this->avatarUrl;
232         }
233
234         try {
235             $avatar = $this->avatar?->getThumb($size, $size, false) ?? $default;
236         } catch (Exception $err) {
237             $avatar = $default;
238         }
239
240         $this->avatarUrl = $avatar;
241
242         return $avatar;
243     }
244
245     /**
246      * Get the avatar for the user.
247      */
248     public function avatar(): BelongsTo
249     {
250         return $this->belongsTo(Image::class, 'image_id');
251     }
252
253     /**
254      * Get the API tokens assigned to this user.
255      */
256     public function apiTokens(): HasMany
257     {
258         return $this->hasMany(ApiToken::class);
259     }
260
261     /**
262      * Get the favourite instances for this user.
263      */
264     public function favourites(): HasMany
265     {
266         return $this->hasMany(Favourite::class);
267     }
268
269     /**
270      * Get the MFA values belonging to this use.
271      */
272     public function mfaValues(): HasMany
273     {
274         return $this->hasMany(MfaValue::class);
275     }
276
277     /**
278      * Get the tracked entity watches for this user.
279      */
280     public function watches(): HasMany
281     {
282         return $this->hasMany(Watch::class);
283     }
284
285     /**
286      * Get the last activity time for this user.
287      */
288     public function scopeWithLastActivityAt(Builder $query)
289     {
290         $query->addSelect(['activities.created_at as last_activity_at'])
291             ->leftJoinSub(function (\Illuminate\Database\Query\Builder $query) {
292                 $query->from('activities')->select('user_id')
293                     ->selectRaw('max(created_at) as created_at')
294                     ->groupBy('user_id');
295             }, 'activities', 'users.id', '=', 'activities.user_id');
296     }
297
298     /**
299      * Get the url for editing this user.
300      */
301     public function getEditUrl(string $path = ''): string
302     {
303         $uri = '/settings/users/' . $this->id . '/' . trim($path, '/');
304
305         return url(rtrim($uri, '/'));
306     }
307
308     /**
309      * Get the url that links to this user's profile.
310      */
311     public function getProfileUrl(): string
312     {
313         return url('/user/' . $this->slug);
314     }
315
316     /**
317      * Get a shortened version of the user's name.
318      */
319     public function getShortName(int $chars = 8): string
320     {
321         if (mb_strlen($this->name) <= $chars) {
322             return $this->name;
323         }
324
325         $splitName = explode(' ', $this->name);
326         if (mb_strlen($splitName[0]) <= $chars) {
327             return $splitName[0];
328         }
329
330         return mb_substr($this->name, 0, max($chars - 2, 0)) . '…';
331     }
332
333     /**
334      * Get the locale for this user.
335      */
336     public function getLocale(): LocaleDefinition
337     {
338         return app()->make(LocaleManager::class)->getForUser($this);
339     }
340
341     /**
342      * Send the password reset notification.
343      *
344      * @param string $token
345      *
346      * @return void
347      */
348     public function sendPasswordResetNotification($token)
349     {
350         $this->notify(new ResetPasswordNotification($token));
351     }
352
353     /**
354      * {@inheritdoc}
355      */
356     public function logDescriptor(): string
357     {
358         return "({$this->id}) {$this->name}";
359     }
360 }