]> BookStack Code Mirror - bookstack/blob - app/Auth/UserRepo.php
Added 'uk' locale
[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
89         // Get avatar from gravatar and save
90         $this->downloadGravatarToUserAvatar($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      * Create a new basic instance of user.
142      * @param array $data
143      * @param boolean $verifyEmail
144      * @return \BookStack\Auth\User
145      */
146     public function create(array $data, $verifyEmail = false)
147     {
148
149         return $this->user->forceCreate([
150             'name'     => $data['name'],
151             'email'    => $data['email'],
152             'password' => bcrypt($data['password']),
153             'email_confirmed' => $verifyEmail
154         ]);
155     }
156
157     /**
158      * Remove the given user from storage, Delete all related content.
159      * @param \BookStack\Auth\User $user
160      * @throws Exception
161      */
162     public function destroy(User $user)
163     {
164         $user->socialAccounts()->delete();
165         $user->delete();
166         
167         // Delete user profile images
168         $profileImages = $images = Image::where('type', '=', 'user')->where('created_by', '=', $user->id)->get();
169         foreach ($profileImages as $image) {
170             Images::destroy($image);
171         }
172     }
173
174     /**
175      * Get the latest activity for a user.
176      * @param \BookStack\Auth\User $user
177      * @param int $count
178      * @param int $page
179      * @return array
180      */
181     public function getActivity(User $user, $count = 20, $page = 0)
182     {
183         return Activity::userActivity($user, $count, $page);
184     }
185
186     /**
187      * Get the recently created content for this given user.
188      * @param \BookStack\Auth\User $user
189      * @param int $count
190      * @return mixed
191      */
192     public function getRecentlyCreated(User $user, $count = 20)
193     {
194         return [
195             'pages'    => $this->entityRepo->getRecentlyCreated('page', $count, 0, function ($query) use ($user) {
196                 $query->where('created_by', '=', $user->id);
197             }),
198             'chapters' => $this->entityRepo->getRecentlyCreated('chapter', $count, 0, function ($query) use ($user) {
199                 $query->where('created_by', '=', $user->id);
200             }),
201             'books'    => $this->entityRepo->getRecentlyCreated('book', $count, 0, function ($query) use ($user) {
202                 $query->where('created_by', '=', $user->id);
203             })
204         ];
205     }
206
207     /**
208      * Get asset created counts for the give user.
209      * @param \BookStack\Auth\User $user
210      * @return array
211      */
212     public function getAssetCounts(User $user)
213     {
214         return [
215             'pages'    => $this->entityRepo->getUserTotalCreated('page', $user),
216             'chapters' => $this->entityRepo->getUserTotalCreated('chapter', $user),
217             'books'    => $this->entityRepo->getUserTotalCreated('book', $user),
218         ];
219     }
220
221     /**
222      * Get the roles in the system that are assignable to a user.
223      * @return mixed
224      */
225     public function getAllRoles()
226     {
227         return $this->role->all();
228     }
229
230     /**
231      * Get all the roles which can be given restricted access to
232      * other entities in the system.
233      * @return mixed
234      */
235     public function getRestrictableRoles()
236     {
237         return $this->role->where('system_name', '!=', 'admin')->get();
238     }
239
240     /**
241      * Get a gravatar image for a user and set it as their avatar.
242      * Does not run if gravatar disabled in config.
243      * @param User $user
244      * @return bool
245      */
246     public function downloadGravatarToUserAvatar(User $user)
247     {
248         // Get avatar from gravatar and save
249         if (!config('services.gravatar')) {
250             return false;
251         }
252
253         try {
254             $avatar = Images::saveUserGravatar($user);
255             $user->avatar()->associate($avatar);
256             $user->save();
257             return true;
258         } catch (Exception $e) {
259             \Log::error('Failed to save user gravatar image');
260             return false;
261         }
262     }
263 }