]> BookStack Code Mirror - bookstack/blob - app/Users/UserRepo.php
HTML: Aligned and standardised DOMDocument usage
[bookstack] / app / Users / UserRepo.php
1 <?php
2
3 namespace BookStack\Users;
4
5 use BookStack\Access\UserInviteService;
6 use BookStack\Activity\ActivityType;
7 use BookStack\Entities\EntityProvider;
8 use BookStack\Exceptions\NotifyException;
9 use BookStack\Exceptions\UserUpdateException;
10 use BookStack\Facades\Activity;
11 use BookStack\Uploads\UserAvatars;
12 use BookStack\Users\Models\Role;
13 use BookStack\Users\Models\User;
14 use Exception;
15 use Illuminate\Support\Facades\Hash;
16 use Illuminate\Support\Facades\Log;
17 use Illuminate\Support\Str;
18
19 class UserRepo
20 {
21     public function __construct(
22         protected UserAvatars $userAvatar,
23         protected UserInviteService $inviteService
24     ) {
25     }
26
27
28     /**
29      * Get a user by their email address.
30      */
31     public function getByEmail(string $email): ?User
32     {
33         return User::query()->where('email', '=', $email)->first();
34     }
35
36     /**
37      * Get a user by their ID.
38      */
39     public function getById(int $id): User
40     {
41         return User::query()->findOrFail($id);
42     }
43
44     /**
45      * Get a user by their slug.
46      */
47     public function getBySlug(string $slug): User
48     {
49         return User::query()->where('slug', '=', $slug)->firstOrFail();
50     }
51
52     /**
53      * Create a new basic instance of user with the given pre-validated data.
54      *
55      * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
56      */
57     public function createWithoutActivity(array $data, bool $emailConfirmed = false): User
58     {
59         $user = new User();
60         $user->name = $data['name'];
61         $user->email = $data['email'];
62         $user->password = Hash::make(empty($data['password']) ? Str::random(32) : $data['password']);
63         $user->email_confirmed = $emailConfirmed;
64         $user->external_auth_id = $data['external_auth_id'] ?? '';
65
66         $user->refreshSlug();
67         $user->save();
68
69         if (!empty($data['language'])) {
70             setting()->putUser($user, 'language', $data['language']);
71         }
72
73         if (isset($data['roles'])) {
74             $this->setUserRoles($user, $data['roles']);
75         }
76
77         $this->downloadAndAssignUserAvatar($user);
78
79         return $user;
80     }
81
82     /**
83      * As per "createWithoutActivity" but records a "create" activity.
84      *
85      * @param array{name: string, email: string, password: ?string, external_auth_id: ?string, language: ?string, roles: ?array} $data
86      */
87     public function create(array $data, bool $sendInvite = false): User
88     {
89         $user = $this->createWithoutActivity($data, true);
90
91         if ($sendInvite) {
92             $this->inviteService->sendInvitation($user);
93         }
94
95         Activity::add(ActivityType::USER_CREATE, $user);
96
97         return $user;
98     }
99
100     /**
101      * Update the given user with the given data.
102      *
103      * @param array{name: ?string, email: ?string, external_auth_id: ?string, password: ?string, roles: ?array<int>, language: ?string} $data
104      *
105      * @throws UserUpdateException
106      */
107     public function update(User $user, array $data, bool $manageUsersAllowed): User
108     {
109         if (!empty($data['name'])) {
110             $user->name = $data['name'];
111             $user->refreshSlug();
112         }
113
114         if (!empty($data['email']) && $manageUsersAllowed) {
115             $user->email = $data['email'];
116         }
117
118         if (!empty($data['external_auth_id']) && $manageUsersAllowed) {
119             $user->external_auth_id = $data['external_auth_id'];
120         }
121
122         if (isset($data['roles']) && $manageUsersAllowed) {
123             $this->setUserRoles($user, $data['roles']);
124         }
125
126         if (!empty($data['password'])) {
127             $user->password = Hash::make($data['password']);
128         }
129
130         if (!empty($data['language'])) {
131             setting()->putUser($user, 'language', $data['language']);
132         }
133
134         $user->save();
135         Activity::add(ActivityType::USER_UPDATE, $user);
136
137         return $user;
138     }
139
140     /**
141      * Remove the given user from storage, Delete all related content.
142      *
143      * @throws Exception
144      */
145     public function destroy(User $user, ?int $newOwnerId = null)
146     {
147         $this->ensureDeletable($user);
148
149         $user->socialAccounts()->delete();
150         $user->apiTokens()->delete();
151         $user->favourites()->delete();
152         $user->mfaValues()->delete();
153         $user->watches()->delete();
154         $user->delete();
155
156         // Delete user profile images
157         $this->userAvatar->destroyAllForUser($user);
158
159         // Delete related activities
160         setting()->deleteUserSettings($user->id);
161
162         if (!empty($newOwnerId)) {
163             $newOwner = User::query()->find($newOwnerId);
164             if (!is_null($newOwner)) {
165                 $this->migrateOwnership($user, $newOwner);
166             }
167         }
168
169         Activity::add(ActivityType::USER_DELETE, $user);
170     }
171
172     /**
173      * @throws NotifyException
174      */
175     protected function ensureDeletable(User $user): void
176     {
177         if ($this->isOnlyAdmin($user)) {
178             throw new NotifyException(trans('errors.users_cannot_delete_only_admin'), $user->getEditUrl());
179         }
180
181         if ($user->system_name === 'public') {
182             throw new NotifyException(trans('errors.users_cannot_delete_guest'), $user->getEditUrl());
183         }
184     }
185
186     /**
187      * Migrate ownership of items in the system from one user to another.
188      */
189     protected function migrateOwnership(User $fromUser, User $toUser)
190     {
191         $entities = (new EntityProvider())->all();
192         foreach ($entities as $instance) {
193             $instance->newQuery()->where('owned_by', '=', $fromUser->id)
194                 ->update(['owned_by' => $toUser->id]);
195         }
196     }
197
198     /**
199      * Get an avatar image for a user and set it as their avatar.
200      * Returns early if avatars disabled or not set in config.
201      */
202     protected function downloadAndAssignUserAvatar(User $user): void
203     {
204         try {
205             $this->userAvatar->fetchAndAssignToUser($user);
206         } catch (Exception $e) {
207             Log::error('Failed to save user avatar image');
208         }
209     }
210
211     /**
212      * Checks if the give user is the only admin.
213      */
214     protected function isOnlyAdmin(User $user): bool
215     {
216         if (!$user->hasSystemRole('admin')) {
217             return false;
218         }
219
220         $adminRole = Role::getSystemRole('admin');
221         if ($adminRole->users()->count() > 1) {
222             return false;
223         }
224
225         return true;
226     }
227
228     /**
229      * Set the assigned user roles via an array of role IDs.
230      *
231      * @throws UserUpdateException
232      */
233     protected function setUserRoles(User $user, array $roles)
234     {
235         $roles = array_filter(array_values($roles));
236
237         if ($this->demotingLastAdmin($user, $roles)) {
238             throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
239         }
240
241         $user->roles()->sync($roles);
242     }
243
244     /**
245      * Check if the given user is the last admin and their new roles no longer
246      * contains the admin role.
247      */
248     protected function demotingLastAdmin(User $user, array $newRoles): bool
249     {
250         if ($this->isOnlyAdmin($user)) {
251             $adminRole = Role::getSystemRole('admin');
252             if (!in_array(strval($adminRole->id), $newRoles)) {
253                 return true;
254             }
255         }
256
257         return false;
258     }
259 }