]> BookStack Code Mirror - bookstack/blob - app/Auth/UserRepo.php
Abstracted user avatar fetching away from gravatar
[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\Uploads\Image;
7 use Exception;
8 use Images;
9
10 class UserRepo
11 {
12
13     protected $user;
14     protected $role;
15     protected $entityRepo;
16
17     /**
18      * UserRepo constructor.
19      * @param User $user
20      * @param Role $role
21      * @param EntityRepo $entityRepo
22      */
23     public function __construct(User $user, Role $role, EntityRepo $entityRepo)
24     {
25         $this->user = $user;
26         $this->role = $role;
27         $this->entityRepo = $entityRepo;
28     }
29
30     /**
31      * @param string $email
32      * @return User|null
33      */
34     public function getByEmail($email)
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->findOrFail($id);
46     }
47
48     /**
49      * Get all the users with their permissions.
50      * @return \Illuminate\Database\Eloquent\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 \Illuminate\Database\Eloquent\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      * @param array $data
81      * @param boolean $verifyEmail
82      * @return \BookStack\Auth\User
83      */
84     public function registerNew(array $data, $verifyEmail = false)
85     {
86         $user = $this->create($data, $verifyEmail);
87         $this->attachDefaultRole($user);
88         $this->downloadAndAssignUserAvatar($user);
89
90         return $user;
91     }
92
93     /**
94      * Give a user the default role. Used when creating a new user.
95      * @param User $user
96      */
97     public function attachDefaultRole(User $user)
98     {
99         $roleId = setting('registration-role');
100         if ($roleId !== false && $user->roles()->where('id', '=', $roleId)->count() === 0) {
101             $user->attachRoleId($roleId);
102         }
103     }
104
105     /**
106      * Assign a user to a system-level role.
107      * @param User $user
108      * @param $systemRoleName
109      * @throws NotFoundException
110      */
111     public function attachSystemRole(User $user, $systemRoleName)
112     {
113         $role = $this->role->newQuery()->where('system_name', '=', $systemRoleName)->first();
114         if ($role === null) {
115             throw new NotFoundException("Role '{$systemRoleName}' not found");
116         }
117         $user->attachRole($role);
118     }
119
120     /**
121      * Checks if the give user is the only admin.
122      * @param \BookStack\Auth\User $user
123      * @return bool
124      */
125     public function isOnlyAdmin(User $user)
126     {
127         if (!$user->hasSystemRole('admin')) {
128             return false;
129         }
130
131         $adminRole = $this->role->getSystemRole('admin');
132         if ($adminRole->users->count() > 1) {
133             return false;
134         }
135         return true;
136     }
137
138     /**
139      * Create a new basic instance of user.
140      * @param array $data
141      * @param boolean $verifyEmail
142      * @return \BookStack\Auth\User
143      */
144     public function create(array $data, $verifyEmail = false)
145     {
146
147         return $this->user->forceCreate([
148             'name'     => $data['name'],
149             'email'    => $data['email'],
150             'password' => bcrypt($data['password']),
151             'email_confirmed' => $verifyEmail
152         ]);
153     }
154
155     /**
156      * Remove the given user from storage, Delete all related content.
157      * @param \BookStack\Auth\User $user
158      * @throws Exception
159      */
160     public function destroy(User $user)
161     {
162         $user->socialAccounts()->delete();
163         $user->delete();
164         
165         // Delete user profile images
166         $profileImages = $images = Image::where('type', '=', 'user')->where('created_by', '=', $user->id)->get();
167         foreach ($profileImages as $image) {
168             Images::destroy($image);
169         }
170     }
171
172     /**
173      * Get the latest activity for a user.
174      * @param \BookStack\Auth\User $user
175      * @param int $count
176      * @param int $page
177      * @return array
178      */
179     public function getActivity(User $user, $count = 20, $page = 0)
180     {
181         return Activity::userActivity($user, $count, $page);
182     }
183
184     /**
185      * Get the recently created content for this given user.
186      * @param \BookStack\Auth\User $user
187      * @param int $count
188      * @return mixed
189      */
190     public function getRecentlyCreated(User $user, $count = 20)
191     {
192         return [
193             'pages'    => $this->entityRepo->getRecentlyCreated('page', $count, 0, function ($query) use ($user) {
194                 $query->where('created_by', '=', $user->id);
195             }),
196             'chapters' => $this->entityRepo->getRecentlyCreated('chapter', $count, 0, function ($query) use ($user) {
197                 $query->where('created_by', '=', $user->id);
198             }),
199             'books'    => $this->entityRepo->getRecentlyCreated('book', $count, 0, function ($query) use ($user) {
200                 $query->where('created_by', '=', $user->id);
201             })
202         ];
203     }
204
205     /**
206      * Get asset created counts for the give user.
207      * @param \BookStack\Auth\User $user
208      * @return array
209      */
210     public function getAssetCounts(User $user)
211     {
212         return [
213             'pages'    => $this->entityRepo->getUserTotalCreated('page', $user),
214             'chapters' => $this->entityRepo->getUserTotalCreated('chapter', $user),
215             'books'    => $this->entityRepo->getUserTotalCreated('book', $user),
216         ];
217     }
218
219     /**
220      * Get the roles in the system that are assignable to a user.
221      * @return mixed
222      */
223     public function getAllRoles()
224     {
225         return $this->role->all();
226     }
227
228     /**
229      * Get all the roles which can be given restricted access to
230      * other entities in the system.
231      * @return mixed
232      */
233     public function getRestrictableRoles()
234     {
235         return $this->role->where('system_name', '!=', 'admin')->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      * @param User $user
242      * @return bool
243      */
244     public function downloadAndAssignUserAvatar(User $user)
245     {
246         if (!Images::avatarFetchEnabled()) {
247             return false;
248         }
249
250         try {
251             $avatar = Images::saveUserAvatar($user);
252             $user->avatar()->associate($avatar);
253             $user->save();
254             return true;
255         } catch (Exception $e) {
256             \Log::error('Failed to save user avatar image');
257             return false;
258         }
259     }
260 }