]> BookStack Code Mirror - bookstack/blob - app/Auth/UserRepo.php
Merge branch 'create-content-meta-tags' of https://github.com/james-geiger/BookStack...
[bookstack] / app / Auth / UserRepo.php
1 <?php namespace BookStack\Auth;
2
3 use Activity;
4 use BookStack\Entities\EntityProvider;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Bookshelf;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Page;
9 use BookStack\Exceptions\NotFoundException;
10 use BookStack\Exceptions\UserUpdateException;
11 use BookStack\Uploads\UserAvatars;
12 use Exception;
13 use Illuminate\Database\Eloquent\Builder;
14 use Illuminate\Database\Eloquent\Collection;
15 use Illuminate\Pagination\LengthAwarePaginator;
16 use Log;
17
18 class UserRepo
19 {
20     protected $userAvatar;
21
22     /**
23      * UserRepo constructor.
24      */
25     public function __construct(UserAvatars $userAvatar)
26     {
27         $this->userAvatar = $userAvatar;
28     }
29
30     /**
31      * Get a user by their email address.
32      */
33     public function getByEmail(string $email): ?User
34     {
35         return User::query()->where('email', '=', $email)->first();
36     }
37
38     /**
39      * Get a user by their ID.
40      */
41     public function getById(int $id): User
42     {
43         return User::query()->findOrFail($id);
44     }
45
46     /**
47      * Get a user by their slug.
48      */
49     public function getBySlug(string $slug): User
50     {
51         return User::query()->where('slug', '=', $slug)->firstOrFail();
52     }
53
54     /**
55      * Get all the users with their permissions.
56      */
57     public function getAllUsers(): Collection
58     {
59         return User::query()->with('roles', 'avatar')->orderBy('name', 'asc')->get();
60     }
61
62     /**
63      * Get all the users with their permissions in a paginated format.
64      */
65     public function getAllUsersPaginatedAndSorted(int $count, array $sortData): LengthAwarePaginator
66     {
67         $sort = $sortData['sort'];
68
69         $query = User::query()->select(['*'])
70             ->withLastActivityAt()
71             ->with(['roles', 'avatar'])
72             ->orderBy($sort, $sortData['order']);
73
74         if ($sortData['search']) {
75             $term = '%' . $sortData['search'] . '%';
76             $query->where(function ($query) use ($term) {
77                 $query->where('name', 'like', $term)
78                     ->orWhere('email', 'like', $term);
79             });
80         }
81
82         return $query->paginate($count);
83     }
84
85      /**
86      * Creates a new user and attaches a role to them.
87      */
88     public function registerNew(array $data, bool $emailConfirmed = false): User
89     {
90         $user = $this->create($data, $emailConfirmed);
91         $user->attachDefaultRole();
92         $this->downloadAndAssignUserAvatar($user);
93
94         return $user;
95     }
96
97     /**
98      * Assign a user to a system-level role.
99      * @throws NotFoundException
100      */
101     public function attachSystemRole(User $user, string $systemRoleName)
102     {
103         $role = Role::getSystemRole($systemRoleName);
104         if (is_null($role)) {
105             throw new NotFoundException("Role '{$systemRoleName}' not found");
106         }
107         $user->attachRole($role);
108     }
109
110     /**
111      * Checks if the give user is the only admin.
112      */
113     public function isOnlyAdmin(User $user): bool
114     {
115         if (!$user->hasSystemRole('admin')) {
116             return false;
117         }
118
119         $adminRole = Role::getSystemRole('admin');
120         if ($adminRole->users()->count() > 1) {
121             return false;
122         }
123
124         return true;
125     }
126
127     /**
128      * Set the assigned user roles via an array of role IDs.
129      * @throws UserUpdateException
130      */
131     public function setUserRoles(User $user, array $roles)
132     {
133         if ($this->demotingLastAdmin($user, $roles)) {
134             throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
135         }
136
137         $user->roles()->sync($roles);
138     }
139
140     /**
141      * Check if the given user is the last admin and their new roles no longer
142      * contains the admin role.
143      */
144     protected function demotingLastAdmin(User $user, array $newRoles) : bool
145     {
146         if ($this->isOnlyAdmin($user)) {
147             $adminRole = Role::getSystemRole('admin');
148             if (!in_array(strval($adminRole->id), $newRoles)) {
149                 return true;
150             }
151         }
152
153         return false;
154     }
155
156     /**
157      * Create a new basic instance of user.
158      */
159     public function create(array $data, bool $emailConfirmed = false): User
160     {
161         $details = [
162             'name'     => $data['name'],
163             'email'    => $data['email'],
164             'password' => bcrypt($data['password']),
165             'email_confirmed' => $emailConfirmed,
166             'external_auth_id' => $data['external_auth_id'] ?? '',
167         ];
168
169         $user = new User();
170         $user->forceFill($details);
171         $user->refreshSlug();
172         $user->save();
173
174         return $user;
175     }
176
177     /**
178      * Remove the given user from storage, Delete all related content.
179      * @throws Exception
180      */
181     public function destroy(User $user, ?int $newOwnerId = null)
182     {
183         $user->socialAccounts()->delete();
184         $user->apiTokens()->delete();
185         $user->favourites()->delete();
186         $user->delete();
187         
188         // Delete user profile images
189         $this->userAvatar->destroyAllForUser($user);
190
191         if (!empty($newOwnerId)) {
192             $newOwner = User::query()->find($newOwnerId);
193             if (!is_null($newOwner)) {
194                 $this->migrateOwnership($user, $newOwner);
195             }
196         }
197     }
198
199     /**
200      * Migrate ownership of items in the system from one user to another.
201      */
202     protected function migrateOwnership(User $fromUser, User $toUser)
203     {
204         $entities = (new EntityProvider)->all();
205         foreach ($entities as $instance) {
206             $instance->newQuery()->where('owned_by', '=', $fromUser->id)
207                 ->update(['owned_by' => $toUser->id]);
208         }
209     }
210
211     /**
212      * Get the latest activity for a user.
213      */
214     public function getActivity(User $user, int $count = 20, int $page = 0): array
215     {
216         return Activity::userActivity($user, $count, $page);
217     }
218
219     /**
220      * Get the recently created content for this given user.
221      */
222     public function getRecentlyCreated(User $user, int $count = 20): array
223     {
224         $query = function (Builder $query) use ($user, $count) {
225             return $query->orderBy('created_at', 'desc')
226                 ->where('created_by', '=', $user->id)
227                 ->take($count)
228                 ->get();
229         };
230
231         return [
232             'pages'    => $query(Page::visible()->where('draft', '=', false)),
233             'chapters' => $query(Chapter::visible()),
234             'books'    => $query(Book::visible()),
235             'shelves'  => $query(Bookshelf::visible()),
236         ];
237     }
238
239     /**
240      * Get asset created counts for the give user.
241      */
242     public function getAssetCounts(User $user): array
243     {
244         $createdBy = ['created_by' => $user->id];
245         return [
246             'pages'    =>  Page::visible()->where($createdBy)->count(),
247             'chapters'    =>  Chapter::visible()->where($createdBy)->count(),
248             'books'    =>  Book::visible()->where($createdBy)->count(),
249             'shelves'    =>  Bookshelf::visible()->where($createdBy)->count(),
250         ];
251     }
252
253     /**
254      * Get the roles in the system that are assignable to a user.
255      */
256     public function getAllRoles(): Collection
257     {
258         return Role::query()->orderBy('display_name', 'asc')->get();
259     }
260
261     /**
262      * Get an avatar image for a user and set it as their avatar.
263      * Returns early if avatars disabled or not set in config.
264      */
265     public function downloadAndAssignUserAvatar(User $user): void
266     {
267         try {
268             $this->userAvatar->fetchAndAssignToUser($user);
269         } catch (Exception $e) {
270             Log::error('Failed to save user avatar image');
271         }
272     }
273 }