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