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