]> BookStack Code Mirror - bookstack/blob - app/Auth/UserRepo.php
Entity Repo & Controller Refactor (#1690)
[bookstack] / app / Auth / UserRepo.php
1 <?php namespace BookStack\Auth;
2
3 use Activity;
4 use BookStack\Entities\Book;
5 use BookStack\Entities\Bookshelf;
6 use BookStack\Entities\Chapter;
7 use BookStack\Entities\Page;
8 use BookStack\Exceptions\NotFoundException;
9 use BookStack\Exceptions\UserUpdateException;
10 use BookStack\Uploads\Image;
11 use Exception;
12 use Illuminate\Database\Eloquent\Builder;
13 use Images;
14 use Log;
15
16 class UserRepo
17 {
18
19     protected $user;
20     protected $role;
21
22     /**
23      * UserRepo constructor.
24      */
25     public function __construct(User $user, Role $role)
26     {
27         $this->user = $user;
28         $this->role = $role;
29     }
30
31     /**
32      * @param string $email
33      * @return User|null
34      */
35     public function getByEmail($email)
36     {
37         return $this->user->where('email', '=', $email)->first();
38     }
39
40     /**
41      * @param int $id
42      * @return User
43      */
44     public function getById($id)
45     {
46         return $this->user->newQuery()->findOrFail($id);
47     }
48
49     /**
50      * Get all the users with their permissions.
51      * @return Builder|static
52      */
53     public function getAllUsers()
54     {
55         return $this->user->with('roles', 'avatar')->orderBy('name', 'asc')->get();
56     }
57
58     /**
59      * Get all the users with their permissions in a paginated format.
60      * @param int $count
61      * @param $sortData
62      * @return Builder|static
63      */
64     public function getAllUsersPaginatedAndSorted($count, $sortData)
65     {
66         $query = $this->user->with('roles', 'avatar')->orderBy($sortData['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      * @param array $data
82      * @param boolean $verifyEmail
83      * @return User
84      */
85     public function registerNew(array $data, $verifyEmail = false)
86     {
87         $user = $this->create($data, $verifyEmail);
88         $this->attachDefaultRole($user);
89         $this->downloadAndAssignUserAvatar($user);
90
91         return $user;
92     }
93
94     /**
95      * Give a user the default role. Used when creating a new user.
96      * @param User $user
97      */
98     public function attachDefaultRole(User $user)
99     {
100         $roleId = setting('registration-role');
101         if ($roleId !== false && $user->roles()->where('id', '=', $roleId)->count() === 0) {
102             $user->attachRoleId($roleId);
103         }
104     }
105
106     /**
107      * Assign a user to a system-level role.
108      * @param User $user
109      * @param $systemRoleName
110      * @throws NotFoundException
111      */
112     public function attachSystemRole(User $user, $systemRoleName)
113     {
114         $role = $this->role->newQuery()->where('system_name', '=', $systemRoleName)->first();
115         if ($role === null) {
116             throw new NotFoundException("Role '{$systemRoleName}' not found");
117         }
118         $user->attachRole($role);
119     }
120
121     /**
122      * Checks if the give user is the only admin.
123      * @param User $user
124      * @return bool
125      */
126     public function isOnlyAdmin(User $user)
127     {
128         if (!$user->hasSystemRole('admin')) {
129             return false;
130         }
131
132         $adminRole = $this->role->getSystemRole('admin');
133         if ($adminRole->users->count() > 1) {
134             return false;
135         }
136         return true;
137     }
138
139     /**
140      * Set the assigned user roles via an array of role IDs.
141      * @param User $user
142      * @param array $roles
143      * @throws UserUpdateException
144      */
145     public function setUserRoles(User $user, array $roles)
146     {
147         if ($this->demotingLastAdmin($user, $roles)) {
148             throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
149         }
150
151         $user->roles()->sync($roles);
152     }
153
154     /**
155      * Check if the given user is the last admin and their new roles no longer
156      * contains the admin role.
157      * @param User $user
158      * @param array $newRoles
159      * @return bool
160      */
161     protected function demotingLastAdmin(User $user, array $newRoles) : bool
162     {
163         if ($this->isOnlyAdmin($user)) {
164             $adminRole = $this->role->getSystemRole('admin');
165             if (!in_array(strval($adminRole->id), $newRoles)) {
166                 return true;
167             }
168         }
169
170         return false;
171     }
172
173     /**
174      * Create a new basic instance of user.
175      * @param array $data
176      * @param boolean $verifyEmail
177      * @return User
178      */
179     public function create(array $data, $verifyEmail = false)
180     {
181         return $this->user->forceCreate([
182             'name'     => $data['name'],
183             'email'    => $data['email'],
184             'password' => bcrypt($data['password']),
185             'email_confirmed' => $verifyEmail
186         ]);
187     }
188
189     /**
190      * Remove the given user from storage, Delete all related content.
191      * @param User $user
192      * @throws Exception
193      */
194     public function destroy(User $user)
195     {
196         $user->socialAccounts()->delete();
197         $user->delete();
198         
199         // Delete user profile images
200         $profileImages = Image::where('type', '=', 'user')->where('uploaded_to', '=', $user->id)->get();
201         foreach ($profileImages as $image) {
202             Images::destroy($image);
203         }
204     }
205
206     /**
207      * Get the latest activity for a user.
208      * @param User $user
209      * @param int $count
210      * @param int $page
211      * @return array
212      */
213     public function getActivity(User $user, $count = 20, $page = 0)
214     {
215         return Activity::userActivity($user, $count, $page);
216     }
217
218     /**
219      * Get the recently created content for this given user.
220      */
221     public function getRecentlyCreated(User $user, int $count = 20): array
222     {
223         $query = function (Builder $query) use ($user, $count) {
224             return $query->orderBy('created_at', 'desc')
225                 ->where('created_by', '=', $user->id)
226                 ->take($count)
227                 ->get();
228         };
229
230         return [
231             'pages'    => $query(Page::visible()->where('draft', '=', false)),
232             'chapters' => $query(Chapter::visible()),
233             'books'    => $query(Book::visible()),
234             'shelves'  => $query(Bookshelf::visible()),
235         ];
236     }
237
238     /**
239      * Get asset created counts for the give user.
240      */
241     public function getAssetCounts(User $user): array
242     {
243         $createdBy = ['created_by' => $user->id];
244         return [
245             'pages'    =>  Page::visible()->where($createdBy)->count(),
246             'chapters'    =>  Chapter::visible()->where($createdBy)->count(),
247             'books'    =>  Book::visible()->where($createdBy)->count(),
248             'shelves'    =>  Bookshelf::visible()->where($createdBy)->count(),
249         ];
250     }
251
252     /**
253      * Get the roles in the system that are assignable to a user.
254      * @return mixed
255      */
256     public function getAllRoles()
257     {
258         return $this->role->newQuery()->orderBy('name', 'asc')->get();
259     }
260
261     /**
262      * Get an avatar image for a user and set it as their avatar.
263      * Returns early if avatars disabled or not set in config.
264      * @param User $user
265      * @return bool
266      */
267     public function downloadAndAssignUserAvatar(User $user)
268     {
269         if (!Images::avatarFetchEnabled()) {
270             return false;
271         }
272
273         try {
274             $avatar = Images::saveUserAvatar($user);
275             $user->avatar()->associate($avatar);
276             $user->save();
277             return true;
278         } catch (Exception $e) {
279             Log::error('Failed to save user avatar image');
280             return false;
281         }
282     }
283 }