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