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