]> BookStack Code Mirror - bookstack/blob - app/Auth/UserRepo.php
Apply fixes from StyleCI
[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 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      */
67     public function getAllUsersPaginatedAndSorted(int $count, array $sortData): LengthAwarePaginator
68     {
69         $sort = $sortData['sort'];
70
71         $query = User::query()->select(['*'])
72             ->withLastActivityAt()
73             ->with(['roles', 'avatar'])
74             ->orderBy($sort, $sortData['order']);
75
76         if ($sortData['search']) {
77             $term = '%' . $sortData['search'] . '%';
78             $query->where(function ($query) use ($term) {
79                 $query->where('name', 'like', $term)
80                     ->orWhere('email', 'like', $term);
81             });
82         }
83
84         return $query->paginate($count);
85     }
86
87     /**
88      * Creates a new user and attaches a role to them.
89      */
90     public function registerNew(array $data, bool $emailConfirmed = false): User
91     {
92         $user = $this->create($data, $emailConfirmed);
93         $user->attachDefaultRole();
94         $this->downloadAndAssignUserAvatar($user);
95
96         return $user;
97     }
98
99     /**
100      * Assign a user to a system-level role.
101      *
102      * @throws NotFoundException
103      */
104     public function attachSystemRole(User $user, string $systemRoleName)
105     {
106         $role = Role::getSystemRole($systemRoleName);
107         if (is_null($role)) {
108             throw new NotFoundException("Role '{$systemRoleName}' not found");
109         }
110         $user->attachRole($role);
111     }
112
113     /**
114      * Checks if the give user is the only admin.
115      */
116     public function isOnlyAdmin(User $user): bool
117     {
118         if (!$user->hasSystemRole('admin')) {
119             return false;
120         }
121
122         $adminRole = Role::getSystemRole('admin');
123         if ($adminRole->users()->count() > 1) {
124             return false;
125         }
126
127         return true;
128     }
129
130     /**
131      * Set the assigned user roles via an array of role IDs.
132      *
133      * @throws UserUpdateException
134      */
135     public function setUserRoles(User $user, array $roles)
136     {
137         if ($this->demotingLastAdmin($user, $roles)) {
138             throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
139         }
140
141         $user->roles()->sync($roles);
142     }
143
144     /**
145      * Check if the given user is the last admin and their new roles no longer
146      * contains the admin role.
147      */
148     protected function demotingLastAdmin(User $user, array $newRoles): bool
149     {
150         if ($this->isOnlyAdmin($user)) {
151             $adminRole = Role::getSystemRole('admin');
152             if (!in_array(strval($adminRole->id), $newRoles)) {
153                 return true;
154             }
155         }
156
157         return false;
158     }
159
160     /**
161      * Create a new basic instance of user.
162      */
163     public function create(array $data, bool $emailConfirmed = false): User
164     {
165         $details = [
166             'name'             => $data['name'],
167             'email'            => $data['email'],
168             'password'         => bcrypt($data['password']),
169             'email_confirmed'  => $emailConfirmed,
170             'external_auth_id' => $data['external_auth_id'] ?? '',
171         ];
172
173         $user = new User();
174         $user->forceFill($details);
175         $user->refreshSlug();
176         $user->save();
177
178         return $user;
179     }
180
181     /**
182      * Remove the given user from storage, Delete all related content.
183      *
184      * @throws Exception
185      */
186     public function destroy(User $user, ?int $newOwnerId = null)
187     {
188         $user->socialAccounts()->delete();
189         $user->apiTokens()->delete();
190         $user->favourites()->delete();
191         $user->delete();
192
193         // Delete user profile images
194         $this->userAvatar->destroyAllForUser($user);
195
196         if (!empty($newOwnerId)) {
197             $newOwner = User::query()->find($newOwnerId);
198             if (!is_null($newOwner)) {
199                 $this->migrateOwnership($user, $newOwner);
200             }
201         }
202     }
203
204     /**
205      * Migrate ownership of items in the system from one user to another.
206      */
207     protected function migrateOwnership(User $fromUser, User $toUser)
208     {
209         $entities = (new EntityProvider())->all();
210         foreach ($entities as $instance) {
211             $instance->newQuery()->where('owned_by', '=', $fromUser->id)
212                 ->update(['owned_by' => $toUser->id]);
213         }
214     }
215
216     /**
217      * Get the latest activity for a user.
218      */
219     public function getActivity(User $user, int $count = 20, int $page = 0): array
220     {
221         return Activity::userActivity($user, $count, $page);
222     }
223
224     /**
225      * Get the recently created content for this given user.
226      */
227     public function getRecentlyCreated(User $user, int $count = 20): array
228     {
229         $query = function (Builder $query) use ($user, $count) {
230             return $query->orderBy('created_at', 'desc')
231                 ->where('created_by', '=', $user->id)
232                 ->take($count)
233                 ->get();
234         };
235
236         return [
237             'pages'    => $query(Page::visible()->where('draft', '=', false)),
238             'chapters' => $query(Chapter::visible()),
239             'books'    => $query(Book::visible()),
240             'shelves'  => $query(Bookshelf::visible()),
241         ];
242     }
243
244     /**
245      * Get asset created counts for the give user.
246      */
247     public function getAssetCounts(User $user): array
248     {
249         $createdBy = ['created_by' => $user->id];
250
251         return [
252             'pages'       => Page::visible()->where($createdBy)->count(),
253             'chapters'    => Chapter::visible()->where($createdBy)->count(),
254             'books'       => Book::visible()->where($createdBy)->count(),
255             'shelves'     => Bookshelf::visible()->where($createdBy)->count(),
256         ];
257     }
258
259     /**
260      * Get the roles in the system that are assignable to a user.
261      */
262     public function getAllRoles(): Collection
263     {
264         return Role::query()->orderBy('display_name', 'asc')->get();
265     }
266
267     /**
268      * Get an avatar image for a user and set it as their avatar.
269      * Returns early if avatars disabled or not set in config.
270      */
271     public function downloadAndAssignUserAvatar(User $user): void
272     {
273         try {
274             $this->userAvatar->fetchAndAssignToUser($user);
275         } catch (Exception $e) {
276             Log::error('Failed to save user avatar image');
277         }
278     }
279 }