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