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