]> BookStack Code Mirror - bookstack/blob - app/Repos/UserRepo.php
Spanish 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
99      */
100     public function attachDefaultRole($user)
101     {
102         $roleId = setting('registration-role');
103         if ($roleId === false) {
104             $roleId = $this->role->first()->id;
105         }
106         $user->attachRoleId($roleId);
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 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 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 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 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 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 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 }