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