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