]> BookStack Code Mirror - bookstack/blob - app/Repos/UserRepo.php
Merge branch 'bug-650' of git://github.com/Abijeet/BookStack into Abijeet-bug-650
[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 = 20, $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) $roleId = $this->role->first()->id;
111         $user->attachRoleId($roleId);
112     }
113
114     /**
115      * Checks if the give user is the only admin.
116      * @param User $user
117      * @return bool
118      */
119     public function isOnlyAdmin(User $user)
120     {
121         if (!$user->hasSystemRole('admin')) return false;
122
123         $adminRole = $this->role->getSystemRole('admin');
124         if ($adminRole->users->count() > 1) return false;
125         return true;
126     }
127
128     /**
129      * Create a new basic instance of user.
130      * @param array $data
131      * @return User
132      */
133     public function create(array $data)
134     {
135         return $this->user->forceCreate([
136             'name'     => $data['name'],
137             'email'    => $data['email'],
138             'password' => bcrypt($data['password']),
139             'email_confirmed' => false
140         ]);
141     }
142
143     /**
144      * Remove the given user from storage, Delete all related content.
145      * @param User $user
146      * @throws Exception
147      */
148     public function destroy(User $user)
149     {
150         $user->socialAccounts()->delete();
151         $user->delete();
152         
153         // Delete user profile images
154         $profileImages = $images = Image::where('type', '=', 'user')->where('created_by', '=', $user->id)->get();
155         foreach ($profileImages as $image) {
156             Images::destroyImage($image);
157         }
158     }
159
160     /**
161      * Get the latest activity for a user.
162      * @param User $user
163      * @param int $count
164      * @param int $page
165      * @return array
166      */
167     public function getActivity(User $user, $count = 20, $page = 0)
168     {
169         return Activity::userActivity($user, $count, $page);
170     }
171
172     /**
173      * Get the recently created content for this given user.
174      * @param User $user
175      * @param int $count
176      * @return mixed
177      */
178     public function getRecentlyCreated(User $user, $count = 20)
179     {
180         return [
181             'pages'    => $this->entityRepo->getRecentlyCreated('page', $count, 0, function ($query) use ($user) {
182                 $query->where('created_by', '=', $user->id);
183             }),
184             'chapters' => $this->entityRepo->getRecentlyCreated('chapter', $count, 0, function ($query) use ($user) {
185                 $query->where('created_by', '=', $user->id);
186             }),
187             'books'    => $this->entityRepo->getRecentlyCreated('book', $count, 0, function ($query) use ($user) {
188                 $query->where('created_by', '=', $user->id);
189             })
190         ];
191     }
192
193     /**
194      * Get asset created counts for the give user.
195      * @param User $user
196      * @return array
197      */
198     public function getAssetCounts(User $user)
199     {
200         return [
201             'pages'    => $this->entityRepo->page->where('created_by', '=', $user->id)->count(),
202             'chapters' => $this->entityRepo->chapter->where('created_by', '=', $user->id)->count(),
203             'books'    => $this->entityRepo->book->where('created_by', '=', $user->id)->count(),
204         ];
205     }
206
207     /**
208      * Get the roles in the system that are assignable to a user.
209      * @return mixed
210      */
211     public function getAllRoles()
212     {
213         return $this->role->all();
214     }
215
216     /**
217      * Get all the roles which can be given restricted access to
218      * other entities in the system.
219      * @return mixed
220      */
221     public function getRestrictableRoles()
222     {
223         return $this->role->where('system_name', '!=', 'admin')->get();
224     }
225
226 }