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