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