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