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