]> BookStack Code Mirror - bookstack/blob - app/Repos/UserRepo.php
Set /app PHP code to PSR-2 standard
[bookstack] / app / Repos / UserRepo.php
1 <?php namespace BookStack\Repos;
2
3 use Activity;
4 use BookStack\Image;
5 use BookStack\Role;
6 use BookStack\User;
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      * @return User
82      */
83     public function registerNew(array $data)
84     {
85         $user = $this->create($data);
86         $this->attachDefaultRole($user);
87
88         // Get avatar from gravatar and save
89         if (!config('services.disable_services')) {
90             try {
91                 $avatar = Images::saveUserGravatar($user);
92                 $user->avatar()->associate($avatar);
93                 $user->save();
94             } catch (Exception $e) {
95                 $user->save();
96                 \Log::error('Failed to save user gravatar image');
97             }
98         }
99
100         return $user;
101     }
102
103     /**
104      * Give a user the default role. Used when creating a new user.
105      * @param $user
106      */
107     public function attachDefaultRole($user)
108     {
109         $roleId = setting('registration-role');
110         if ($roleId === false) {
111             $roleId = $this->role->first()->id;
112         }
113         $user->attachRoleId($roleId);
114     }
115
116     /**
117      * Checks if the give user is the only admin.
118      * @param User $user
119      * @return bool
120      */
121     public function isOnlyAdmin(User $user)
122     {
123         if (!$user->hasSystemRole('admin')) {
124             return false;
125         }
126
127         $adminRole = $this->role->getSystemRole('admin');
128         if ($adminRole->users->count() > 1) {
129             return false;
130         }
131         return true;
132     }
133
134     /**
135      * Create a new basic instance of user.
136      * @param array $data
137      * @return User
138      */
139     public function create(array $data)
140     {
141         return $this->user->forceCreate([
142             'name'     => $data['name'],
143             'email'    => $data['email'],
144             'password' => bcrypt($data['password']),
145             'email_confirmed' => false
146         ]);
147     }
148
149     /**
150      * Remove the given user from storage, Delete all related content.
151      * @param User $user
152      * @throws Exception
153      */
154     public function destroy(User $user)
155     {
156         $user->socialAccounts()->delete();
157         $user->delete();
158         
159         // Delete user profile images
160         $profileImages = $images = Image::where('type', '=', 'user')->where('created_by', '=', $user->id)->get();
161         foreach ($profileImages as $image) {
162             Images::destroyImage($image);
163         }
164     }
165
166     /**
167      * Get the latest activity for a user.
168      * @param User $user
169      * @param int $count
170      * @param int $page
171      * @return array
172      */
173     public function getActivity(User $user, $count = 20, $page = 0)
174     {
175         return Activity::userActivity($user, $count, $page);
176     }
177
178     /**
179      * Get the recently created content for this given user.
180      * @param User $user
181      * @param int $count
182      * @return mixed
183      */
184     public function getRecentlyCreated(User $user, $count = 20)
185     {
186         return [
187             'pages'    => $this->entityRepo->getRecentlyCreated('page', $count, 0, function ($query) use ($user) {
188                 $query->where('created_by', '=', $user->id);
189             }),
190             'chapters' => $this->entityRepo->getRecentlyCreated('chapter', $count, 0, function ($query) use ($user) {
191                 $query->where('created_by', '=', $user->id);
192             }),
193             'books'    => $this->entityRepo->getRecentlyCreated('book', $count, 0, function ($query) use ($user) {
194                 $query->where('created_by', '=', $user->id);
195             })
196         ];
197     }
198
199     /**
200      * Get asset created counts for the give user.
201      * @param User $user
202      * @return array
203      */
204     public function getAssetCounts(User $user)
205     {
206         return [
207             'pages'    => $this->entityRepo->page->where('created_by', '=', $user->id)->count(),
208             'chapters' => $this->entityRepo->chapter->where('created_by', '=', $user->id)->count(),
209             'books'    => $this->entityRepo->book->where('created_by', '=', $user->id)->count(),
210         ];
211     }
212
213     /**
214      * Get the roles in the system that are assignable to a user.
215      * @return mixed
216      */
217     public function getAllRoles()
218     {
219         return $this->role->all();
220     }
221
222     /**
223      * Get all the roles which can be given restricted access to
224      * other entities in the system.
225      * @return mixed
226      */
227     public function getRestrictableRoles()
228     {
229         return $this->role->where('system_name', '!=', 'admin')->get();
230     }
231 }