]> BookStack Code Mirror - bookstack/blob - app/Auth/UserRepo.php
Make building of search results work for multi-byte encoded characters
[bookstack] / app / Auth / UserRepo.php
1 <?php
2
3 namespace BookStack\Auth;
4
5 use Activity;
6 use BookStack\Entities\EntityProvider;
7 use BookStack\Entities\Models\Book;
8 use BookStack\Entities\Models\Bookshelf;
9 use BookStack\Entities\Models\Chapter;
10 use BookStack\Entities\Models\Page;
11 use BookStack\Exceptions\NotFoundException;
12 use BookStack\Exceptions\UserUpdateException;
13 use BookStack\Uploads\UserAvatars;
14 use Exception;
15 use Illuminate\Database\Eloquent\Builder;
16 use Illuminate\Database\Eloquent\Collection;
17 use Illuminate\Pagination\LengthAwarePaginator;
18 use Illuminate\Support\Facades\Log;
19
20 class UserRepo
21 {
22     protected $userAvatar;
23
24     /**
25      * UserRepo constructor.
26      */
27     public function __construct(UserAvatars $userAvatar)
28     {
29         $this->userAvatar = $userAvatar;
30     }
31
32     /**
33      * Get a user by their email address.
34      */
35     public function getByEmail(string $email): ?User
36     {
37         return User::query()->where('email', '=', $email)->first();
38     }
39
40     /**
41      * Get a user by their ID.
42      */
43     public function getById(int $id): User
44     {
45         return User::query()->findOrFail($id);
46     }
47
48     /**
49      * Get a user by their slug.
50      */
51     public function getBySlug(string $slug): User
52     {
53         return User::query()->where('slug', '=', $slug)->firstOrFail();
54     }
55
56     /**
57      * Get all the users with their permissions.
58      */
59     public function getAllUsers(): Collection
60     {
61         return User::query()->with('roles', 'avatar')->orderBy('name', 'asc')->get();
62     }
63
64     /**
65      * Get all the users with their permissions in a paginated format.
66      * Note: Due to the use of email search this should only be used when
67      * user is assumed to be trusted. (Admin users).
68      * Email search can be abused to extract email addresses.
69      */
70     public function getAllUsersPaginatedAndSorted(int $count, array $sortData): LengthAwarePaginator
71     {
72         $sort = $sortData['sort'];
73
74         $query = User::query()->select(['*'])
75             ->scopes(['withLastActivityAt'])
76             ->with(['roles', 'avatar'])
77             ->withCount('mfaValues')
78             ->orderBy($sort, $sortData['order']);
79
80         if ($sortData['search']) {
81             $term = '%' . $sortData['search'] . '%';
82             $query->where(function ($query) use ($term) {
83                 $query->where('name', 'like', $term)
84                     ->orWhere('email', 'like', $term);
85             });
86         }
87
88         return $query->paginate($count);
89     }
90
91     /**
92      * Creates a new user and attaches a role to them.
93      */
94     public function registerNew(array $data, bool $emailConfirmed = false): User
95     {
96         $user = $this->create($data, $emailConfirmed);
97         $user->attachDefaultRole();
98         $this->downloadAndAssignUserAvatar($user);
99
100         return $user;
101     }
102
103     /**
104      * Assign a user to a system-level role.
105      *
106      * @throws NotFoundException
107      */
108     public function attachSystemRole(User $user, string $systemRoleName)
109     {
110         $role = Role::getSystemRole($systemRoleName);
111         if (is_null($role)) {
112             throw new NotFoundException("Role '{$systemRoleName}' not found");
113         }
114         $user->attachRole($role);
115     }
116
117     /**
118      * Checks if the give user is the only admin.
119      */
120     public function isOnlyAdmin(User $user): bool
121     {
122         if (!$user->hasSystemRole('admin')) {
123             return false;
124         }
125
126         $adminRole = Role::getSystemRole('admin');
127         if ($adminRole->users()->count() > 1) {
128             return false;
129         }
130
131         return true;
132     }
133
134     /**
135      * Set the assigned user roles via an array of role IDs.
136      *
137      * @throws UserUpdateException
138      */
139     public function setUserRoles(User $user, array $roles)
140     {
141         if ($this->demotingLastAdmin($user, $roles)) {
142             throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
143         }
144
145         $user->roles()->sync($roles);
146     }
147
148     /**
149      * Check if the given user is the last admin and their new roles no longer
150      * contains the admin role.
151      */
152     protected function demotingLastAdmin(User $user, array $newRoles): bool
153     {
154         if ($this->isOnlyAdmin($user)) {
155             $adminRole = Role::getSystemRole('admin');
156             if (!in_array(strval($adminRole->id), $newRoles)) {
157                 return true;
158             }
159         }
160
161         return false;
162     }
163
164     /**
165      * Create a new basic instance of user.
166      */
167     public function create(array $data, bool $emailConfirmed = false): User
168     {
169         $details = [
170             'name'             => $data['name'],
171             'email'            => $data['email'],
172             'password'         => bcrypt($data['password']),
173             'email_confirmed'  => $emailConfirmed,
174             'external_auth_id' => $data['external_auth_id'] ?? '',
175         ];
176
177         $user = new User();
178         $user->forceFill($details);
179         $user->refreshSlug();
180         $user->save();
181
182         return $user;
183     }
184
185     /**
186      * Remove the given user from storage, Delete all related content.
187      *
188      * @throws Exception
189      */
190     public function destroy(User $user, ?int $newOwnerId = null)
191     {
192         $user->socialAccounts()->delete();
193         $user->apiTokens()->delete();
194         $user->favourites()->delete();
195         $user->mfaValues()->delete();
196         $user->delete();
197
198         // Delete user profile images
199         $this->userAvatar->destroyAllForUser($user);
200
201         if (!empty($newOwnerId)) {
202             $newOwner = User::query()->find($newOwnerId);
203             if (!is_null($newOwner)) {
204                 $this->migrateOwnership($user, $newOwner);
205             }
206         }
207     }
208
209     /**
210      * Migrate ownership of items in the system from one user to another.
211      */
212     protected function migrateOwnership(User $fromUser, User $toUser)
213     {
214         $entities = (new EntityProvider())->all();
215         foreach ($entities as $instance) {
216             $instance->newQuery()->where('owned_by', '=', $fromUser->id)
217                 ->update(['owned_by' => $toUser->id]);
218         }
219     }
220
221     /**
222      * Get the latest activity for a user.
223      */
224     public function getActivity(User $user, int $count = 20, int $page = 0): array
225     {
226         return Activity::userActivity($user, $count, $page);
227     }
228
229     /**
230      * Get the recently created content for this given user.
231      */
232     public function getRecentlyCreated(User $user, int $count = 20): array
233     {
234         $query = function (Builder $query) use ($user, $count) {
235             return $query->orderBy('created_at', 'desc')
236                 ->where('created_by', '=', $user->id)
237                 ->take($count)
238                 ->get();
239         };
240
241         return [
242             'pages'    => $query(Page::visible()->where('draft', '=', false)),
243             'chapters' => $query(Chapter::visible()),
244             'books'    => $query(Book::visible()),
245             'shelves'  => $query(Bookshelf::visible()),
246         ];
247     }
248
249     /**
250      * Get asset created counts for the give user.
251      */
252     public function getAssetCounts(User $user): array
253     {
254         $createdBy = ['created_by' => $user->id];
255
256         return [
257             'pages'       => Page::visible()->where($createdBy)->count(),
258             'chapters'    => Chapter::visible()->where($createdBy)->count(),
259             'books'       => Book::visible()->where($createdBy)->count(),
260             'shelves'     => Bookshelf::visible()->where($createdBy)->count(),
261         ];
262     }
263
264     /**
265      * Get the roles in the system that are assignable to a user.
266      */
267     public function getAllRoles(): Collection
268     {
269         return Role::query()->orderBy('display_name', 'asc')->get();
270     }
271
272     /**
273      * Get an avatar image for a user and set it as their avatar.
274      * Returns early if avatars disabled or not set in config.
275      */
276     public function downloadAndAssignUserAvatar(User $user): void
277     {
278         try {
279             $this->userAvatar->fetchAndAssignToUser($user);
280         } catch (Exception $e) {
281             Log::error('Failed to save user avatar image');
282         }
283     }
284 }