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