Completed
Push — master ( d4a0af...760b28 )
by Blizzz
25:12 queued 24:34
created
lib/private/Group/Group.php 1 patch
Indentation   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -35,292 +35,292 @@
 block discarded – undo
35 35
 use OCP\Group\Backend\ICountDisabledInGroup;
36 36
 
37 37
 class Group implements IGroup {
38
-	/** @var null|string  */
39
-	protected $displayName;
38
+    /** @var null|string  */
39
+    protected $displayName;
40 40
 
41
-	/**
42
-	 * @var string $id
43
-	 */
44
-	private $gid;
41
+    /**
42
+     * @var string $id
43
+     */
44
+    private $gid;
45 45
 
46
-	/**
47
-	 * @var \OC\User\User[] $users
48
-	 */
49
-	private $users = array();
46
+    /**
47
+     * @var \OC\User\User[] $users
48
+     */
49
+    private $users = array();
50 50
 
51
-	/**
52
-	 * @var bool $usersLoaded
53
-	 */
54
-	private $usersLoaded;
51
+    /**
52
+     * @var bool $usersLoaded
53
+     */
54
+    private $usersLoaded;
55 55
 
56
-	/**
57
-	 * @var \OC\Group\Backend[]|\OC\Group\Database[] $backend
58
-	 */
59
-	private $backends;
56
+    /**
57
+     * @var \OC\Group\Backend[]|\OC\Group\Database[] $backend
58
+     */
59
+    private $backends;
60 60
 
61
-	/**
62
-	 * @var \OC\Hooks\PublicEmitter $emitter
63
-	 */
64
-	private $emitter;
61
+    /**
62
+     * @var \OC\Hooks\PublicEmitter $emitter
63
+     */
64
+    private $emitter;
65 65
 
66
-	/**
67
-	 * @var \OC\User\Manager $userManager
68
-	 */
69
-	private $userManager;
66
+    /**
67
+     * @var \OC\User\Manager $userManager
68
+     */
69
+    private $userManager;
70 70
 
71
-	/**
72
-	 * @param string $gid
73
-	 * @param \OC\Group\Backend[] $backends
74
-	 * @param \OC\User\Manager $userManager
75
-	 * @param \OC\Hooks\PublicEmitter $emitter
76
-	 * @param string $displayName
77
-	 */
78
-	public function __construct($gid, $backends, $userManager, $emitter = null, $displayName = null) {
79
-		$this->gid = $gid;
80
-		$this->backends = $backends;
81
-		$this->userManager = $userManager;
82
-		$this->emitter = $emitter;
83
-		$this->displayName = $displayName;
84
-	}
71
+    /**
72
+     * @param string $gid
73
+     * @param \OC\Group\Backend[] $backends
74
+     * @param \OC\User\Manager $userManager
75
+     * @param \OC\Hooks\PublicEmitter $emitter
76
+     * @param string $displayName
77
+     */
78
+    public function __construct($gid, $backends, $userManager, $emitter = null, $displayName = null) {
79
+        $this->gid = $gid;
80
+        $this->backends = $backends;
81
+        $this->userManager = $userManager;
82
+        $this->emitter = $emitter;
83
+        $this->displayName = $displayName;
84
+    }
85 85
 
86
-	public function getGID() {
87
-		return $this->gid;
88
-	}
86
+    public function getGID() {
87
+        return $this->gid;
88
+    }
89 89
 
90
-	public function getDisplayName() {
91
-		if (is_null($this->displayName)) {
92
-			return $this->gid;
93
-		}
94
-		return $this->displayName;
95
-	}
90
+    public function getDisplayName() {
91
+        if (is_null($this->displayName)) {
92
+            return $this->gid;
93
+        }
94
+        return $this->displayName;
95
+    }
96 96
 
97
-	/**
98
-	 * get all users in the group
99
-	 *
100
-	 * @return \OC\User\User[]
101
-	 */
102
-	public function getUsers() {
103
-		if ($this->usersLoaded) {
104
-			return $this->users;
105
-		}
97
+    /**
98
+     * get all users in the group
99
+     *
100
+     * @return \OC\User\User[]
101
+     */
102
+    public function getUsers() {
103
+        if ($this->usersLoaded) {
104
+            return $this->users;
105
+        }
106 106
 
107
-		$userIds = array();
108
-		foreach ($this->backends as $backend) {
109
-			$diff = array_diff(
110
-				$backend->usersInGroup($this->gid),
111
-				$userIds
112
-			);
113
-			if ($diff) {
114
-				$userIds = array_merge($userIds, $diff);
115
-			}
116
-		}
107
+        $userIds = array();
108
+        foreach ($this->backends as $backend) {
109
+            $diff = array_diff(
110
+                $backend->usersInGroup($this->gid),
111
+                $userIds
112
+            );
113
+            if ($diff) {
114
+                $userIds = array_merge($userIds, $diff);
115
+            }
116
+        }
117 117
 
118
-		$this->users = $this->getVerifiedUsers($userIds);
119
-		$this->usersLoaded = true;
120
-		return $this->users;
121
-	}
118
+        $this->users = $this->getVerifiedUsers($userIds);
119
+        $this->usersLoaded = true;
120
+        return $this->users;
121
+    }
122 122
 
123
-	/**
124
-	 * check if a user is in the group
125
-	 *
126
-	 * @param IUser $user
127
-	 * @return bool
128
-	 */
129
-	public function inGroup(IUser $user) {
130
-		if (isset($this->users[$user->getUID()])) {
131
-			return true;
132
-		}
133
-		foreach ($this->backends as $backend) {
134
-			if ($backend->inGroup($user->getUID(), $this->gid)) {
135
-				$this->users[$user->getUID()] = $user;
136
-				return true;
137
-			}
138
-		}
139
-		return false;
140
-	}
123
+    /**
124
+     * check if a user is in the group
125
+     *
126
+     * @param IUser $user
127
+     * @return bool
128
+     */
129
+    public function inGroup(IUser $user) {
130
+        if (isset($this->users[$user->getUID()])) {
131
+            return true;
132
+        }
133
+        foreach ($this->backends as $backend) {
134
+            if ($backend->inGroup($user->getUID(), $this->gid)) {
135
+                $this->users[$user->getUID()] = $user;
136
+                return true;
137
+            }
138
+        }
139
+        return false;
140
+    }
141 141
 
142
-	/**
143
-	 * add a user to the group
144
-	 *
145
-	 * @param IUser $user
146
-	 */
147
-	public function addUser(IUser $user) {
148
-		if ($this->inGroup($user)) {
149
-			return;
150
-		}
142
+    /**
143
+     * add a user to the group
144
+     *
145
+     * @param IUser $user
146
+     */
147
+    public function addUser(IUser $user) {
148
+        if ($this->inGroup($user)) {
149
+            return;
150
+        }
151 151
 
152
-		if ($this->emitter) {
153
-			$this->emitter->emit('\OC\Group', 'preAddUser', array($this, $user));
154
-		}
155
-		foreach ($this->backends as $backend) {
156
-			if ($backend->implementsActions(\OC\Group\Backend::ADD_TO_GROUP)) {
157
-				$backend->addToGroup($user->getUID(), $this->gid);
158
-				if ($this->users) {
159
-					$this->users[$user->getUID()] = $user;
160
-				}
161
-				if ($this->emitter) {
162
-					$this->emitter->emit('\OC\Group', 'postAddUser', array($this, $user));
163
-				}
164
-				return;
165
-			}
166
-		}
167
-	}
152
+        if ($this->emitter) {
153
+            $this->emitter->emit('\OC\Group', 'preAddUser', array($this, $user));
154
+        }
155
+        foreach ($this->backends as $backend) {
156
+            if ($backend->implementsActions(\OC\Group\Backend::ADD_TO_GROUP)) {
157
+                $backend->addToGroup($user->getUID(), $this->gid);
158
+                if ($this->users) {
159
+                    $this->users[$user->getUID()] = $user;
160
+                }
161
+                if ($this->emitter) {
162
+                    $this->emitter->emit('\OC\Group', 'postAddUser', array($this, $user));
163
+                }
164
+                return;
165
+            }
166
+        }
167
+    }
168 168
 
169
-	/**
170
-	 * remove a user from the group
171
-	 *
172
-	 * @param \OC\User\User $user
173
-	 */
174
-	public function removeUser($user) {
175
-		$result = false;
176
-		if ($this->emitter) {
177
-			$this->emitter->emit('\OC\Group', 'preRemoveUser', array($this, $user));
178
-		}
179
-		foreach ($this->backends as $backend) {
180
-			if ($backend->implementsActions(\OC\Group\Backend::REMOVE_FROM_GOUP) and $backend->inGroup($user->getUID(), $this->gid)) {
181
-				$backend->removeFromGroup($user->getUID(), $this->gid);
182
-				$result = true;
183
-			}
184
-		}
185
-		if ($result) {
186
-			if ($this->emitter) {
187
-				$this->emitter->emit('\OC\Group', 'postRemoveUser', array($this, $user));
188
-			}
189
-			if ($this->users) {
190
-				foreach ($this->users as $index => $groupUser) {
191
-					if ($groupUser->getUID() === $user->getUID()) {
192
-						unset($this->users[$index]);
193
-						return;
194
-					}
195
-				}
196
-			}
197
-		}
198
-	}
169
+    /**
170
+     * remove a user from the group
171
+     *
172
+     * @param \OC\User\User $user
173
+     */
174
+    public function removeUser($user) {
175
+        $result = false;
176
+        if ($this->emitter) {
177
+            $this->emitter->emit('\OC\Group', 'preRemoveUser', array($this, $user));
178
+        }
179
+        foreach ($this->backends as $backend) {
180
+            if ($backend->implementsActions(\OC\Group\Backend::REMOVE_FROM_GOUP) and $backend->inGroup($user->getUID(), $this->gid)) {
181
+                $backend->removeFromGroup($user->getUID(), $this->gid);
182
+                $result = true;
183
+            }
184
+        }
185
+        if ($result) {
186
+            if ($this->emitter) {
187
+                $this->emitter->emit('\OC\Group', 'postRemoveUser', array($this, $user));
188
+            }
189
+            if ($this->users) {
190
+                foreach ($this->users as $index => $groupUser) {
191
+                    if ($groupUser->getUID() === $user->getUID()) {
192
+                        unset($this->users[$index]);
193
+                        return;
194
+                    }
195
+                }
196
+            }
197
+        }
198
+    }
199 199
 
200
-	/**
201
-	 * search for users in the group by userid
202
-	 *
203
-	 * @param string $search
204
-	 * @param int $limit
205
-	 * @param int $offset
206
-	 * @return \OC\User\User[]
207
-	 */
208
-	public function searchUsers($search, $limit = null, $offset = null) {
209
-		$users = array();
210
-		foreach ($this->backends as $backend) {
211
-			$userIds = $backend->usersInGroup($this->gid, $search, $limit, $offset);
212
-			$users += $this->getVerifiedUsers($userIds);
213
-			if (!is_null($limit) and $limit <= 0) {
214
-				return array_values($users);
215
-			}
216
-		}
217
-		return array_values($users);
218
-	}
200
+    /**
201
+     * search for users in the group by userid
202
+     *
203
+     * @param string $search
204
+     * @param int $limit
205
+     * @param int $offset
206
+     * @return \OC\User\User[]
207
+     */
208
+    public function searchUsers($search, $limit = null, $offset = null) {
209
+        $users = array();
210
+        foreach ($this->backends as $backend) {
211
+            $userIds = $backend->usersInGroup($this->gid, $search, $limit, $offset);
212
+            $users += $this->getVerifiedUsers($userIds);
213
+            if (!is_null($limit) and $limit <= 0) {
214
+                return array_values($users);
215
+            }
216
+        }
217
+        return array_values($users);
218
+    }
219 219
 
220
-	/**
221
-	 * returns the number of users matching the search string
222
-	 *
223
-	 * @param string $search
224
-	 * @return int|bool
225
-	 */
226
-	public function count($search = '') {
227
-		$users = false;
228
-		foreach ($this->backends as $backend) {
229
-			if($backend->implementsActions(\OC\Group\Backend::COUNT_USERS)) {
230
-				if($users === false) {
231
-					//we could directly add to a bool variable, but this would
232
-					//be ugly
233
-					$users = 0;
234
-				}
235
-				$users += $backend->countUsersInGroup($this->gid, $search);
236
-			}
237
-		}
238
-		return $users;
239
-	}
220
+    /**
221
+     * returns the number of users matching the search string
222
+     *
223
+     * @param string $search
224
+     * @return int|bool
225
+     */
226
+    public function count($search = '') {
227
+        $users = false;
228
+        foreach ($this->backends as $backend) {
229
+            if($backend->implementsActions(\OC\Group\Backend::COUNT_USERS)) {
230
+                if($users === false) {
231
+                    //we could directly add to a bool variable, but this would
232
+                    //be ugly
233
+                    $users = 0;
234
+                }
235
+                $users += $backend->countUsersInGroup($this->gid, $search);
236
+            }
237
+        }
238
+        return $users;
239
+    }
240 240
 
241
-	/**
242
-	 * returns the number of disabled users
243
-	 *
244
-	 * @return int|bool
245
-	 */
246
-	public function countDisabled() {
247
-		$users = false;
248
-		foreach ($this->backends as $backend) {
249
-			if($backend instanceOf ICountDisabledInGroup) {
250
-				if($users === false) {
251
-					//we could directly add to a bool variable, but this would
252
-					//be ugly
253
-					$users = 0;
254
-				}
255
-				$users += $backend->countDisabledInGroup($this->gid);
256
-			}
257
-		}
258
-		return $users;
259
-	}
241
+    /**
242
+     * returns the number of disabled users
243
+     *
244
+     * @return int|bool
245
+     */
246
+    public function countDisabled() {
247
+        $users = false;
248
+        foreach ($this->backends as $backend) {
249
+            if($backend instanceOf ICountDisabledInGroup) {
250
+                if($users === false) {
251
+                    //we could directly add to a bool variable, but this would
252
+                    //be ugly
253
+                    $users = 0;
254
+                }
255
+                $users += $backend->countDisabledInGroup($this->gid);
256
+            }
257
+        }
258
+        return $users;
259
+    }
260 260
 
261
-	/**
262
-	 * search for users in the group by displayname
263
-	 *
264
-	 * @param string $search
265
-	 * @param int $limit
266
-	 * @param int $offset
267
-	 * @return \OC\User\User[]
268
-	 */
269
-	public function searchDisplayName($search, $limit = null, $offset = null) {
270
-		$users = array();
271
-		foreach ($this->backends as $backend) {
272
-			$userIds = $backend->usersInGroup($this->gid, $search, $limit, $offset);
273
-			$users = $this->getVerifiedUsers($userIds);
274
-			if (!is_null($limit) and $limit <= 0) {
275
-				return array_values($users);
276
-			}
277
-		}
278
-		return array_values($users);
279
-	}
261
+    /**
262
+     * search for users in the group by displayname
263
+     *
264
+     * @param string $search
265
+     * @param int $limit
266
+     * @param int $offset
267
+     * @return \OC\User\User[]
268
+     */
269
+    public function searchDisplayName($search, $limit = null, $offset = null) {
270
+        $users = array();
271
+        foreach ($this->backends as $backend) {
272
+            $userIds = $backend->usersInGroup($this->gid, $search, $limit, $offset);
273
+            $users = $this->getVerifiedUsers($userIds);
274
+            if (!is_null($limit) and $limit <= 0) {
275
+                return array_values($users);
276
+            }
277
+        }
278
+        return array_values($users);
279
+    }
280 280
 
281
-	/**
282
-	 * delete the group
283
-	 *
284
-	 * @return bool
285
-	 */
286
-	public function delete() {
287
-		// Prevent users from deleting group admin
288
-		if ($this->getGID() === 'admin') {
289
-			return false;
290
-		}
281
+    /**
282
+     * delete the group
283
+     *
284
+     * @return bool
285
+     */
286
+    public function delete() {
287
+        // Prevent users from deleting group admin
288
+        if ($this->getGID() === 'admin') {
289
+            return false;
290
+        }
291 291
 
292
-		$result = false;
293
-		if ($this->emitter) {
294
-			$this->emitter->emit('\OC\Group', 'preDelete', array($this));
295
-		}
296
-		foreach ($this->backends as $backend) {
297
-			if ($backend->implementsActions(\OC\Group\Backend::DELETE_GROUP)) {
298
-				$result = true;
299
-				$backend->deleteGroup($this->gid);
300
-			}
301
-		}
302
-		if ($result and $this->emitter) {
303
-			$this->emitter->emit('\OC\Group', 'postDelete', array($this));
304
-		}
305
-		return $result;
306
-	}
292
+        $result = false;
293
+        if ($this->emitter) {
294
+            $this->emitter->emit('\OC\Group', 'preDelete', array($this));
295
+        }
296
+        foreach ($this->backends as $backend) {
297
+            if ($backend->implementsActions(\OC\Group\Backend::DELETE_GROUP)) {
298
+                $result = true;
299
+                $backend->deleteGroup($this->gid);
300
+            }
301
+        }
302
+        if ($result and $this->emitter) {
303
+            $this->emitter->emit('\OC\Group', 'postDelete', array($this));
304
+        }
305
+        return $result;
306
+    }
307 307
 
308
-	/**
309
-	 * returns all the Users from an array that really exists
310
-	 * @param string[] $userIds an array containing user IDs
311
-	 * @return \OC\User\User[] an Array with the userId as Key and \OC\User\User as value
312
-	 */
313
-	private function getVerifiedUsers($userIds) {
314
-		if (!is_array($userIds)) {
315
-			return array();
316
-		}
317
-		$users = array();
318
-		foreach ($userIds as $userId) {
319
-			$user = $this->userManager->get($userId);
320
-			if (!is_null($user)) {
321
-				$users[$userId] = $user;
322
-			}
323
-		}
324
-		return $users;
325
-	}
308
+    /**
309
+     * returns all the Users from an array that really exists
310
+     * @param string[] $userIds an array containing user IDs
311
+     * @return \OC\User\User[] an Array with the userId as Key and \OC\User\User as value
312
+     */
313
+    private function getVerifiedUsers($userIds) {
314
+        if (!is_array($userIds)) {
315
+            return array();
316
+        }
317
+        $users = array();
318
+        foreach ($userIds as $userId) {
319
+            $user = $this->userManager->get($userId);
320
+            if (!is_null($user)) {
321
+                $users[$userId] = $user;
322
+            }
323
+        }
324
+        return $users;
325
+    }
326 326
 }
Please login to merge, or discard this patch.
lib/public/Group/Backend/ICountDisabledInGroup.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -29,8 +29,8 @@
 block discarded – undo
29 29
  */
30 30
 interface ICountDisabledInGroup {
31 31
 
32
-	/**
33
-	 * @since 14.0.0
34
-	 */
35
-	public function countDisabledInGroup(string $gid): int;
32
+    /**
33
+     * @since 14.0.0
34
+     */
35
+    public function countDisabledInGroup(string $gid): int;
36 36
 }
Please login to merge, or discard this patch.
lib/public/IGroup.php 1 patch
Indentation   +83 added lines, -83 removed lines patch added patch discarded remove patch
@@ -33,97 +33,97 @@
 block discarded – undo
33 33
  * @since 8.0.0
34 34
  */
35 35
 interface IGroup {
36
-	/**
37
-	 * @return string
38
-	 * @since 8.0.0
39
-	 */
40
-	public function getGID();
36
+    /**
37
+     * @return string
38
+     * @since 8.0.0
39
+     */
40
+    public function getGID();
41 41
 
42
-	/**
43
-	 * Returns the group display name
44
-	 *
45
-	 * @return string
46
-	 * @since 12.0.0
47
-	 */
48
-	public function getDisplayName();
42
+    /**
43
+     * Returns the group display name
44
+     *
45
+     * @return string
46
+     * @since 12.0.0
47
+     */
48
+    public function getDisplayName();
49 49
 
50
-	/**
51
-	 * get all users in the group
52
-	 *
53
-	 * @return \OCP\IUser[]
54
-	 * @since 8.0.0
55
-	 */
56
-	public function getUsers();
50
+    /**
51
+     * get all users in the group
52
+     *
53
+     * @return \OCP\IUser[]
54
+     * @since 8.0.0
55
+     */
56
+    public function getUsers();
57 57
 
58
-	/**
59
-	 * check if a user is in the group
60
-	 *
61
-	 * @param \OCP\IUser $user
62
-	 * @return bool
63
-	 * @since 8.0.0
64
-	 */
65
-	public function inGroup(IUser $user);
58
+    /**
59
+     * check if a user is in the group
60
+     *
61
+     * @param \OCP\IUser $user
62
+     * @return bool
63
+     * @since 8.0.0
64
+     */
65
+    public function inGroup(IUser $user);
66 66
 
67
-	/**
68
-	 * add a user to the group
69
-	 *
70
-	 * @param \OCP\IUser $user
71
-	 * @since 8.0.0
72
-	 */
73
-	public function addUser(IUser $user);
67
+    /**
68
+     * add a user to the group
69
+     *
70
+     * @param \OCP\IUser $user
71
+     * @since 8.0.0
72
+     */
73
+    public function addUser(IUser $user);
74 74
 
75
-	/**
76
-	 * remove a user from the group
77
-	 *
78
-	 * @param \OCP\IUser $user
79
-	 * @since 8.0.0
80
-	 */
81
-	public function removeUser($user);
75
+    /**
76
+     * remove a user from the group
77
+     *
78
+     * @param \OCP\IUser $user
79
+     * @since 8.0.0
80
+     */
81
+    public function removeUser($user);
82 82
 
83
-	/**
84
-	 * search for users in the group by userid
85
-	 *
86
-	 * @param string $search
87
-	 * @param int $limit
88
-	 * @param int $offset
89
-	 * @return \OCP\IUser[]
90
-	 * @since 8.0.0
91
-	 */
92
-	public function searchUsers($search, $limit = null, $offset = null);
83
+    /**
84
+     * search for users in the group by userid
85
+     *
86
+     * @param string $search
87
+     * @param int $limit
88
+     * @param int $offset
89
+     * @return \OCP\IUser[]
90
+     * @since 8.0.0
91
+     */
92
+    public function searchUsers($search, $limit = null, $offset = null);
93 93
 
94
-	/**
95
-	 * returns the number of users matching the search string
96
-	 *
97
-	 * @param string $search
98
-	 * @return int|bool
99
-	 * @since 8.0.0
100
-	 */
101
-	public function count($search = '');
94
+    /**
95
+     * returns the number of users matching the search string
96
+     *
97
+     * @param string $search
98
+     * @return int|bool
99
+     * @since 8.0.0
100
+     */
101
+    public function count($search = '');
102 102
 
103
-	/**
104
-	 * returns the number of disabled users
105
-	 *
106
-	 * @return int|bool
107
-	 * @since 14.0.0
108
-	 */
109
-	public function countDisabled();
103
+    /**
104
+     * returns the number of disabled users
105
+     *
106
+     * @return int|bool
107
+     * @since 14.0.0
108
+     */
109
+    public function countDisabled();
110 110
 
111
-	/**
112
-	 * search for users in the group by displayname
113
-	 *
114
-	 * @param string $search
115
-	 * @param int $limit
116
-	 * @param int $offset
117
-	 * @return \OCP\IUser[]
118
-	 * @since 8.0.0
119
-	 */
120
-	public function searchDisplayName($search, $limit = null, $offset = null);
111
+    /**
112
+     * search for users in the group by displayname
113
+     *
114
+     * @param string $search
115
+     * @param int $limit
116
+     * @param int $offset
117
+     * @return \OCP\IUser[]
118
+     * @since 8.0.0
119
+     */
120
+    public function searchDisplayName($search, $limit = null, $offset = null);
121 121
 
122
-	/**
123
-	 * delete the group
124
-	 *
125
-	 * @return bool
126
-	 * @since 8.0.0
127
-	 */
128
-	public function delete();
122
+    /**
123
+     * delete the group
124
+     *
125
+     * @return bool
126
+     * @since 8.0.0
127
+     */
128
+    public function delete();
129 129
 }
Please login to merge, or discard this patch.
apps/provisioning_api/lib/Controller/AUserData.php 1 patch
Indentation   +145 added lines, -145 removed lines patch added patch discarded remove patch
@@ -35,152 +35,152 @@
 block discarded – undo
35 35
 
36 36
 abstract class AUserData extends OCSController {
37 37
 
38
-	/** @var IUserManager */
39
-	protected $userManager;
40
-	/** @var IConfig */
41
-	protected $config;
42
-	/** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
43
-	protected $groupManager;
44
-	/** @var IUserSession */
45
-	protected $userSession;
46
-	/** @var AccountManager */
47
-	protected $accountManager;
48
-
49
-	/**
50
-	 * @param string $appName
51
-	 * @param IRequest $request
52
-	 * @param IUserManager $userManager
53
-	 * @param IConfig $config
54
-	 * @param IGroupManager $groupManager
55
-	 * @param IUserSession $userSession
56
-	 * @param AccountManager $accountManager
57
-	 */
58
-	public function __construct(string $appName,
59
-								IRequest $request,
60
-								IUserManager $userManager,
61
-								IConfig $config,
62
-								IGroupManager $groupManager,
63
-								IUserSession $userSession,
64
-								AccountManager $accountManager) {
65
-		parent::__construct($appName, $request);
66
-
67
-		$this->userManager = $userManager;
68
-		$this->config = $config;
69
-		$this->groupManager = $groupManager;
70
-		$this->userSession = $userSession;
71
-		$this->accountManager = $accountManager;
72
-	}
73
-
74
-	/**
75
-	 * creates a array with all user data
76
-	 *
77
-	 * @param $userId
78
-	 * @return array
79
-	 * @throws OCSException
80
-	 */
81
-	protected function getUserData(string $userId): array {
82
-		$currentLoggedInUser = $this->userSession->getUser();
83
-
84
-		$data = [];
85
-
86
-		// Check if the target user exists
87
-		$targetUserObject = $this->userManager->get($userId);
88
-		if($targetUserObject === null) {
89
-			throw new OCSNotFoundException('User does not exist');
90
-		}
91
-
92
-		// Should be at least Admin Or SubAdmin!
93
-		if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())
94
-			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
95
-				$data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true') === 'true';
96
-		} else {
97
-			// Check they are looking up themselves
98
-			if ($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
99
-				return $data;
100
-			}
101
-		}
102
-
103
-		// Get groups data
104
-		$userAccount = $this->accountManager->getUser($targetUserObject);
105
-		$groups = $this->groupManager->getUserGroups($targetUserObject);
106
-		$gids = [];
107
-		foreach ($groups as $group) {
108
-			$gids[] = $group->getDisplayName();
109
-		}
110
-
111
-		// Find the data
112
-		$data['id'] = $targetUserObject->getUID();
113
-		$data['storageLocation'] = $targetUserObject->getHome();
114
-		$data['lastLogin'] = $targetUserObject->getLastLogin() * 1000;
115
-		$data['backend'] = $targetUserObject->getBackendClassName();
116
-		$data['subadmin'] = $this->getUserSubAdminGroupsData($targetUserObject->getUID());
117
-		$data['quota'] = $this->fillStorageInfo($targetUserObject->getUID());
118
-		$data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
119
-		$data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
120
-		$data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
121
-		$data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
122
-		$data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
123
-		$data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
124
-		$data['groups'] = $gids;
125
-		$data['language'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'lang');
126
-
127
-		return $data;
38
+    /** @var IUserManager */
39
+    protected $userManager;
40
+    /** @var IConfig */
41
+    protected $config;
42
+    /** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
43
+    protected $groupManager;
44
+    /** @var IUserSession */
45
+    protected $userSession;
46
+    /** @var AccountManager */
47
+    protected $accountManager;
48
+
49
+    /**
50
+     * @param string $appName
51
+     * @param IRequest $request
52
+     * @param IUserManager $userManager
53
+     * @param IConfig $config
54
+     * @param IGroupManager $groupManager
55
+     * @param IUserSession $userSession
56
+     * @param AccountManager $accountManager
57
+     */
58
+    public function __construct(string $appName,
59
+                                IRequest $request,
60
+                                IUserManager $userManager,
61
+                                IConfig $config,
62
+                                IGroupManager $groupManager,
63
+                                IUserSession $userSession,
64
+                                AccountManager $accountManager) {
65
+        parent::__construct($appName, $request);
66
+
67
+        $this->userManager = $userManager;
68
+        $this->config = $config;
69
+        $this->groupManager = $groupManager;
70
+        $this->userSession = $userSession;
71
+        $this->accountManager = $accountManager;
128 72
     }
129 73
 
130
-	/**
131
-	 * Get the groups a user is a subadmin of
132
-	 *
133
-	 * @param string $userId
134
-	 * @return array
135
-	 * @throws OCSException
136
-	 */
137
-	protected function getUserSubAdminGroupsData(string $userId): array {
138
-		$user = $this->userManager->get($userId);
139
-		// Check if the user exists
140
-		if($user === null) {
141
-			throw new OCSNotFoundException('User does not exist');
142
-		}
143
-
144
-		// Get the subadmin groups
145
-		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
146
-		$groups = [];
147
-		foreach ($subAdminGroups as $key => $group) {
148
-			$groups[] = $group->getGID();
149
-		}
150
-
151
-		return $groups;
152
-	}
153
-
154
-	/**
155
-	 * @param string $userId
156
-	 * @return array
157
-	 * @throws \OCP\Files\NotFoundException
158
-	 */
159
-	protected function fillStorageInfo(string $userId): array {
160
-		try {
161
-			\OC_Util::tearDownFS();
162
-			\OC_Util::setupFS($userId);
163
-			$storage = OC_Helper::getStorageInfo('/');
164
-			$data = [
165
-				'free' => $storage['free'],
166
-				'used' => $storage['used'],
167
-				'total' => $storage['total'],
168
-				'relative' => $storage['relative'],
169
-				'quota' => $storage['quota'],
170
-			];
171
-		} catch (NotFoundException $ex) {
172
-			// User fs is not setup yet
173
-			$user = $this->userManager->get($userId);
174
-			if ($user === null) {
175
-				throw new OCSException('User does not exist', 101);
176
-			}
177
-			$quota = OC_Helper::computerFileSize($user->getQuota());
178
-			$data = [
179
-				'quota' => $quota ? $quota : 'none',
180
-				'used' => 0
181
-			];
182
-		}
183
-		return $data;
184
-	}
74
+    /**
75
+     * creates a array with all user data
76
+     *
77
+     * @param $userId
78
+     * @return array
79
+     * @throws OCSException
80
+     */
81
+    protected function getUserData(string $userId): array {
82
+        $currentLoggedInUser = $this->userSession->getUser();
83
+
84
+        $data = [];
85
+
86
+        // Check if the target user exists
87
+        $targetUserObject = $this->userManager->get($userId);
88
+        if($targetUserObject === null) {
89
+            throw new OCSNotFoundException('User does not exist');
90
+        }
91
+
92
+        // Should be at least Admin Or SubAdmin!
93
+        if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())
94
+            || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
95
+                $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true') === 'true';
96
+        } else {
97
+            // Check they are looking up themselves
98
+            if ($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
99
+                return $data;
100
+            }
101
+        }
102
+
103
+        // Get groups data
104
+        $userAccount = $this->accountManager->getUser($targetUserObject);
105
+        $groups = $this->groupManager->getUserGroups($targetUserObject);
106
+        $gids = [];
107
+        foreach ($groups as $group) {
108
+            $gids[] = $group->getDisplayName();
109
+        }
110
+
111
+        // Find the data
112
+        $data['id'] = $targetUserObject->getUID();
113
+        $data['storageLocation'] = $targetUserObject->getHome();
114
+        $data['lastLogin'] = $targetUserObject->getLastLogin() * 1000;
115
+        $data['backend'] = $targetUserObject->getBackendClassName();
116
+        $data['subadmin'] = $this->getUserSubAdminGroupsData($targetUserObject->getUID());
117
+        $data['quota'] = $this->fillStorageInfo($targetUserObject->getUID());
118
+        $data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
119
+        $data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
120
+        $data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
121
+        $data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
122
+        $data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
123
+        $data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
124
+        $data['groups'] = $gids;
125
+        $data['language'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'lang');
126
+
127
+        return $data;
128
+    }
129
+
130
+    /**
131
+     * Get the groups a user is a subadmin of
132
+     *
133
+     * @param string $userId
134
+     * @return array
135
+     * @throws OCSException
136
+     */
137
+    protected function getUserSubAdminGroupsData(string $userId): array {
138
+        $user = $this->userManager->get($userId);
139
+        // Check if the user exists
140
+        if($user === null) {
141
+            throw new OCSNotFoundException('User does not exist');
142
+        }
143
+
144
+        // Get the subadmin groups
145
+        $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
146
+        $groups = [];
147
+        foreach ($subAdminGroups as $key => $group) {
148
+            $groups[] = $group->getGID();
149
+        }
150
+
151
+        return $groups;
152
+    }
153
+
154
+    /**
155
+     * @param string $userId
156
+     * @return array
157
+     * @throws \OCP\Files\NotFoundException
158
+     */
159
+    protected function fillStorageInfo(string $userId): array {
160
+        try {
161
+            \OC_Util::tearDownFS();
162
+            \OC_Util::setupFS($userId);
163
+            $storage = OC_Helper::getStorageInfo('/');
164
+            $data = [
165
+                'free' => $storage['free'],
166
+                'used' => $storage['used'],
167
+                'total' => $storage['total'],
168
+                'relative' => $storage['relative'],
169
+                'quota' => $storage['quota'],
170
+            ];
171
+        } catch (NotFoundException $ex) {
172
+            // User fs is not setup yet
173
+            $user = $this->userManager->get($userId);
174
+            if ($user === null) {
175
+                throw new OCSException('User does not exist', 101);
176
+            }
177
+            $quota = OC_Helper::computerFileSize($user->getQuota());
178
+            $data = [
179
+                'quota' => $quota ? $quota : 'none',
180
+                'used' => 0
181
+            ];
182
+        }
183
+        return $data;
184
+    }
185 185
 
186 186
 }
Please login to merge, or discard this patch.
apps/provisioning_api/lib/Controller/UsersController.php 1 patch
Indentation   +845 added lines, -845 removed lines patch added patch discarded remove patch
@@ -52,849 +52,849 @@
 block discarded – undo
52 52
 
53 53
 class UsersController extends AUserData {
54 54
 
55
-	/** @var IAppManager */
56
-	private $appManager;
57
-	/** @var ILogger */
58
-	private $logger;
59
-	/** @var IFactory */
60
-	private $l10nFactory;
61
-	/** @var NewUserMailHelper */
62
-	private $newUserMailHelper;
63
-	/** @var FederatedFileSharingFactory */
64
-	private $federatedFileSharingFactory;
65
-	/** @var ISecureRandom */
66
-	private $secureRandom;
67
-
68
-	/**
69
-	 * @param string $appName
70
-	 * @param IRequest $request
71
-	 * @param IUserManager $userManager
72
-	 * @param IConfig $config
73
-	 * @param IAppManager $appManager
74
-	 * @param IGroupManager $groupManager
75
-	 * @param IUserSession $userSession
76
-	 * @param AccountManager $accountManager
77
-	 * @param ILogger $logger
78
-	 * @param IFactory $l10nFactory
79
-	 * @param NewUserMailHelper $newUserMailHelper
80
-	 * @param FederatedFileSharingFactory $federatedFileSharingFactory
81
-	 * @param ISecureRandom $secureRandom
82
-	 */
83
-	public function __construct(string $appName,
84
-								IRequest $request,
85
-								IUserManager $userManager,
86
-								IConfig $config,
87
-								IAppManager $appManager,
88
-								IGroupManager $groupManager,
89
-								IUserSession $userSession,
90
-								AccountManager $accountManager,
91
-								ILogger $logger,
92
-								IFactory $l10nFactory,
93
-								NewUserMailHelper $newUserMailHelper,
94
-								FederatedFileSharingFactory $federatedFileSharingFactory,
95
-								ISecureRandom $secureRandom) {
96
-		parent::__construct($appName,
97
-							$request,
98
-							$userManager,
99
-							$config,
100
-							$groupManager,
101
-							$userSession,
102
-							$accountManager);
103
-
104
-		$this->appManager = $appManager;
105
-		$this->logger = $logger;
106
-		$this->l10nFactory = $l10nFactory;
107
-		$this->newUserMailHelper = $newUserMailHelper;
108
-		$this->federatedFileSharingFactory = $federatedFileSharingFactory;
109
-		$this->secureRandom = $secureRandom;
110
-	}
111
-
112
-	/**
113
-	 * @NoAdminRequired
114
-	 *
115
-	 * returns a list of users
116
-	 *
117
-	 * @param string $search
118
-	 * @param int $limit
119
-	 * @param int $offset
120
-	 * @return DataResponse
121
-	 */
122
-	public function getUsers(string $search = '', $limit = null, $offset = 0): DataResponse {
123
-		$user = $this->userSession->getUser();
124
-		$users = [];
125
-
126
-		// Admin? Or SubAdmin?
127
-		$uid = $user->getUID();
128
-		$subAdminManager = $this->groupManager->getSubAdmin();
129
-		if ($this->groupManager->isAdmin($uid)){
130
-			$users = $this->userManager->search($search, $limit, $offset);
131
-		} else if ($subAdminManager->isSubAdmin($user)) {
132
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
133
-			foreach ($subAdminOfGroups as $key => $group) {
134
-				$subAdminOfGroups[$key] = $group->getGID();
135
-			}
136
-
137
-			$users = [];
138
-			foreach ($subAdminOfGroups as $group) {
139
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
140
-			}
141
-		}
142
-
143
-		$users = array_keys($users);
144
-
145
-		return new DataResponse([
146
-			'users' => $users
147
-		]);
148
-	}
149
-
150
-	/**
151
-	 * @NoAdminRequired
152
-	 *
153
-	 * returns a list of users and their data
154
-	 */
155
-	public function getUsersDetails(string $search = '', $limit = null, $offset = 0): DataResponse {
156
-		$user = $this->userSession->getUser();
157
-		$users = [];
158
-
159
-		// Admin? Or SubAdmin?
160
-		$uid = $user->getUID();
161
-		$subAdminManager = $this->groupManager->getSubAdmin();
162
-		if ($this->groupManager->isAdmin($uid)){
163
-			$users = $this->userManager->search($search, $limit, $offset);
164
-		} else if ($subAdminManager->isSubAdmin($user)) {
165
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
166
-			foreach ($subAdminOfGroups as $key => $group) {
167
-				$subAdminOfGroups[$key] = $group->getGID();
168
-			}
169
-
170
-			$users = [];
171
-			foreach ($subAdminOfGroups as $group) {
172
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
173
-			}
174
-		}
175
-
176
-		$users = array_keys($users);
177
-		$usersDetails = [];
178
-		foreach ($users as $key => $userId) {
179
-			$userData = $this->getUserData($userId);
180
-			// Do not insert empty entry
181
-			if (!empty($userData)) {
182
-				$usersDetails[$userId] = $userData;
183
-			} else {
184
-				// Logged user does not have permissions to see this user
185
-				// only showing its id
186
-				$usersDetails[$userId] = ['id' => $userId];
187
-			}
188
-		}
189
-
190
-		return new DataResponse([
191
-			'users' => $usersDetails
192
-		]);
193
-	}
194
-
195
-	/**
196
-	 * @PasswordConfirmationRequired
197
-	 * @NoAdminRequired
198
-	 *
199
-	 * @param string $userid
200
-	 * @param string $password
201
-	 * @param string $email
202
-	 * @param array $groups
203
-	 * @param array $subadmins
204
-	 * @param string $quota
205
-	 * @param string $language
206
-	 * @return DataResponse
207
-	 * @throws OCSException
208
-	 */
209
-	public function addUser(string $userid,
210
-							string $password = '',
211
-							string $email = '',
212
-							array $groups = [],
213
-							array $subadmin = [],
214
-							string $quota = '',
215
-							string $language = ''): DataResponse {
216
-		$user = $this->userSession->getUser();
217
-		$isAdmin = $this->groupManager->isAdmin($user->getUID());
218
-		$subAdminManager = $this->groupManager->getSubAdmin();
219
-
220
-		if ($this->userManager->userExists($userid)) {
221
-			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
222
-			throw new OCSException('User already exists', 102);
223
-		}
224
-
225
-		if ($groups !== []) {
226
-			foreach ($groups as $group) {
227
-				if (!$this->groupManager->groupExists($group)) {
228
-					throw new OCSException('group '.$group.' does not exist', 104);
229
-				}
230
-				if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
231
-					throw new OCSException('insufficient privileges for group '. $group, 105);
232
-				}
233
-			}
234
-		} else {
235
-			if (!$isAdmin) {
236
-				throw new OCSException('no group specified (required for subadmins)', 106);
237
-			}
238
-		}
239
-
240
-		$subadminGroups = [];
241
-		if ($subadmin !== []) {
242
-			foreach ($subadmin as $groupid) {
243
-				$group = $this->groupManager->get($groupid);
244
-				// Check if group exists
245
-				if ($group === null) {
246
-					throw new OCSException('Subadmin group does not exist',  102);
247
-				}
248
-				// Check if trying to make subadmin of admin group
249
-				if ($group->getGID() === 'admin') {
250
-					throw new OCSException('Cannot create subadmins for admin group', 103);
251
-				}
252
-				// Check if has permission to promote subadmins
253
-				if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) {
254
-					throw new OCSForbiddenException('No permissions to promote subadmins');
255
-				}
256
-				$subadminGroups[] = $group;
257
-			}
258
-		}
259
-
260
-		$generatePasswordResetToken = false;
261
-		if ($password === '') {
262
-			if ($email === '') {
263
-				throw new OCSException('To send a password link to the user an email address is required.', 108);
264
-			}
265
-
266
-			$password = $this->secureRandom->generate(10);
267
-			// Make sure we pass the password_policy
268
-			$password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
269
-			$generatePasswordResetToken = true;
270
-		}
271
-
272
-		try {
273
-			$newUser = $this->userManager->createUser($userid, $password);
274
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
275
-
276
-			foreach ($groups as $group) {
277
-				$this->groupManager->get($group)->addUser($newUser);
278
-				$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
279
-			}
280
-			foreach ($subadminGroups as $group) {
281
-				$subAdminManager->createSubAdmin($newUser, $group);
282
-			}
283
-
284
-			if ($quota !== '') {
285
-				$this->editUser($userid, 'quota', $quota);
286
-			}
287
-
288
-			if ($language !== '') {
289
-				$this->editUser($userid, 'language', $language);
290
-			}
291
-
292
-			// Send new user mail only if a mail is set
293
-			if ($email !== '') {
294
-				$newUser->setEMailAddress($email);
295
-				try {
296
-					$emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
297
-					$this->newUserMailHelper->sendMail($newUser, $emailTemplate);
298
-				} catch (\Exception $e) {
299
-					$this->logger->logException($e, [
300
-						'message' => "Can't send new user mail to $email",
301
-						'level' => ILogger::ERROR,
302
-						'app' => 'ocs_api',
303
-					]);
304
-					throw new OCSException('Unable to send the invitation mail', 109);
305
-				}
306
-			}
307
-
308
-			return new DataResponse();
309
-
310
-		} catch (HintException $e ) {
311
-			$this->logger->logException($e, [
312
-				'message' => 'Failed addUser attempt with hint exception.',
313
-				'level' => ILogger::WARN,
314
-				'app' => 'ocs_api',
315
-			]);
316
-			throw new OCSException($e->getHint(), 107);
317
-		} catch (\Exception $e) {
318
-			$this->logger->logException($e, [
319
-				'message' => 'Failed addUser attempt with exception.',
320
-				'level' => ILogger::ERROR,
321
-				'app' => 'ocs_api',
322
-			]);
323
-			throw new OCSException('Bad request', 101);
324
-		}
325
-	}
326
-
327
-	/**
328
-	 * @NoAdminRequired
329
-	 * @NoSubAdminRequired
330
-	 *
331
-	 * gets user info
332
-	 *
333
-	 * @param string $userId
334
-	 * @return DataResponse
335
-	 * @throws OCSException
336
-	 */
337
-	public function getUser(string $userId): DataResponse {
338
-		$data = $this->getUserData($userId);
339
-		// getUserData returns empty array if not enough permissions
340
-		if (empty($data)) {
341
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
342
-		}
343
-		return new DataResponse($data);
344
-	}
345
-
346
-	/**
347
-	 * @NoAdminRequired
348
-	 * @NoSubAdminRequired
349
-	 *
350
-	 * gets user info from the currently logged in user
351
-	 *
352
-	 * @return DataResponse
353
-	 * @throws OCSException
354
-	 */
355
-	public function getCurrentUser(): DataResponse {
356
-		$user = $this->userSession->getUser();
357
-		if ($user) {
358
-			$data =  $this->getUserData($user->getUID());
359
-			// rename "displayname" to "display-name" only for this call to keep
360
-			// the API stable.
361
-			$data['display-name'] = $data['displayname'];
362
-			unset($data['displayname']);
363
-			return new DataResponse($data);
364
-
365
-		}
366
-
367
-		throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
368
-	}
369
-
370
-	/**
371
-	 * @NoAdminRequired
372
-	 * @NoSubAdminRequired
373
-	 */
374
-	public function getEditableFields(): DataResponse {
375
-		$permittedFields = [];
376
-
377
-		// Editing self (display, email)
378
-		if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
379
-			$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
380
-			$permittedFields[] = AccountManager::PROPERTY_EMAIL;
381
-		}
382
-
383
-		if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
384
-			$federatedFileSharing = $this->federatedFileSharingFactory->get();
385
-			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
386
-			if ($shareProvider->isLookupServerUploadEnabled()) {
387
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
388
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
389
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
390
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
391
-			}
392
-		}
393
-
394
-		return new DataResponse($permittedFields);
395
-	}
396
-
397
-	/**
398
-	 * @NoAdminRequired
399
-	 * @NoSubAdminRequired
400
-	 * @PasswordConfirmationRequired
401
-	 *
402
-	 * edit users
403
-	 *
404
-	 * @param string $userId
405
-	 * @param string $key
406
-	 * @param string $value
407
-	 * @return DataResponse
408
-	 * @throws OCSException
409
-	 */
410
-	public function editUser(string $userId, string $key, string $value): DataResponse {
411
-		$currentLoggedInUser = $this->userSession->getUser();
412
-
413
-		$targetUser = $this->userManager->get($userId);
414
-		if ($targetUser === null) {
415
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
416
-		}
417
-
418
-		$permittedFields = [];
419
-		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
420
-			// Editing self (display, email)
421
-			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
422
-				$permittedFields[] = 'display';
423
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
424
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
425
-			}
426
-
427
-			$permittedFields[] = 'password';
428
-			if ($this->config->getSystemValue('force_language', false) === false ||
429
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
430
-				$permittedFields[] = 'language';
431
-			}
432
-
433
-			if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
434
-				$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
435
-				$shareProvider = $federatedFileSharing->getFederatedShareProvider();
436
-				if ($shareProvider->isLookupServerUploadEnabled()) {
437
-					$permittedFields[] = AccountManager::PROPERTY_PHONE;
438
-					$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
439
-					$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
440
-					$permittedFields[] = AccountManager::PROPERTY_TWITTER;
441
-				}
442
-			}
443
-
444
-			// If admin they can edit their own quota
445
-			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
446
-				$permittedFields[] = 'quota';
447
-			}
448
-		} else {
449
-			// Check if admin / subadmin
450
-			$subAdminManager = $this->groupManager->getSubAdmin();
451
-			if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
452
-			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
453
-				// They have permissions over the user
454
-				$permittedFields[] = 'display';
455
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
456
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
457
-				$permittedFields[] = 'password';
458
-				$permittedFields[] = 'language';
459
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
460
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
461
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
462
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
463
-				$permittedFields[] = 'quota';
464
-			} else {
465
-				// No rights
466
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
467
-			}
468
-		}
469
-		// Check if permitted to edit this field
470
-		if (!in_array($key, $permittedFields)) {
471
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
472
-		}
473
-		// Process the edit
474
-		switch($key) {
475
-			case 'display':
476
-			case AccountManager::PROPERTY_DISPLAYNAME:
477
-				$targetUser->setDisplayName($value);
478
-				break;
479
-			case 'quota':
480
-				$quota = $value;
481
-				if ($quota !== 'none' && $quota !== 'default') {
482
-					if (is_numeric($quota)) {
483
-						$quota = (float) $quota;
484
-					} else {
485
-						$quota = \OCP\Util::computerFileSize($quota);
486
-					}
487
-					if ($quota === false) {
488
-						throw new OCSException('Invalid quota value '.$value, 103);
489
-					}
490
-					if ($quota === 0) {
491
-						$quota = 'default';
492
-					}else if ($quota === -1) {
493
-						$quota = 'none';
494
-					} else {
495
-						$quota = \OCP\Util::humanFileSize($quota);
496
-					}
497
-				}
498
-				$targetUser->setQuota($quota);
499
-				break;
500
-			case 'password':
501
-				$targetUser->setPassword($value);
502
-				break;
503
-			case 'language':
504
-				$languagesCodes = $this->l10nFactory->findAvailableLanguages();
505
-				if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
506
-					throw new OCSException('Invalid language', 102);
507
-				}
508
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
509
-				break;
510
-			case AccountManager::PROPERTY_EMAIL:
511
-				if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
512
-					$targetUser->setEMailAddress($value);
513
-				} else {
514
-					throw new OCSException('', 102);
515
-				}
516
-				break;
517
-			case AccountManager::PROPERTY_PHONE:
518
-			case AccountManager::PROPERTY_ADDRESS:
519
-			case AccountManager::PROPERTY_WEBSITE:
520
-			case AccountManager::PROPERTY_TWITTER:
521
-				$userAccount = $this->accountManager->getUser($targetUser);
522
-				if ($userAccount[$key]['value'] !== $value) {
523
-					$userAccount[$key]['value'] = $value;
524
-					$this->accountManager->updateUser($targetUser, $userAccount);
525
-				}
526
-				break;
527
-			default:
528
-				throw new OCSException('', 103);
529
-		}
530
-		return new DataResponse();
531
-	}
532
-
533
-	/**
534
-	 * @PasswordConfirmationRequired
535
-	 * @NoAdminRequired
536
-	 *
537
-	 * @param string $userId
538
-	 * @return DataResponse
539
-	 * @throws OCSException
540
-	 */
541
-	public function deleteUser(string $userId): DataResponse {
542
-		$currentLoggedInUser = $this->userSession->getUser();
543
-
544
-		$targetUser = $this->userManager->get($userId);
545
-
546
-		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
547
-			throw new OCSException('', 101);
548
-		}
549
-
550
-		// If not permitted
551
-		$subAdminManager = $this->groupManager->getSubAdmin();
552
-		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
553
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
554
-		}
555
-
556
-		// Go ahead with the delete
557
-		if ($targetUser->delete()) {
558
-			return new DataResponse();
559
-		} else {
560
-			throw new OCSException('', 101);
561
-		}
562
-	}
563
-
564
-	/**
565
-	 * @PasswordConfirmationRequired
566
-	 * @NoAdminRequired
567
-	 *
568
-	 * @param string $userId
569
-	 * @return DataResponse
570
-	 * @throws OCSException
571
-	 * @throws OCSForbiddenException
572
-	 */
573
-	public function disableUser(string $userId): DataResponse {
574
-		return $this->setEnabled($userId, false);
575
-	}
576
-
577
-	/**
578
-	 * @PasswordConfirmationRequired
579
-	 * @NoAdminRequired
580
-	 *
581
-	 * @param string $userId
582
-	 * @return DataResponse
583
-	 * @throws OCSException
584
-	 * @throws OCSForbiddenException
585
-	 */
586
-	public function enableUser(string $userId): DataResponse {
587
-		return $this->setEnabled($userId, true);
588
-	}
589
-
590
-	/**
591
-	 * @param string $userId
592
-	 * @param bool $value
593
-	 * @return DataResponse
594
-	 * @throws OCSException
595
-	 */
596
-	private function setEnabled(string $userId, bool $value): DataResponse {
597
-		$currentLoggedInUser = $this->userSession->getUser();
598
-
599
-		$targetUser = $this->userManager->get($userId);
600
-		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
601
-			throw new OCSException('', 101);
602
-		}
603
-
604
-		// If not permitted
605
-		$subAdminManager = $this->groupManager->getSubAdmin();
606
-		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
607
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
608
-		}
609
-
610
-		// enable/disable the user now
611
-		$targetUser->setEnabled($value);
612
-		return new DataResponse();
613
-	}
614
-
615
-	/**
616
-	 * @NoAdminRequired
617
-	 * @NoSubAdminRequired
618
-	 *
619
-	 * @param string $userId
620
-	 * @return DataResponse
621
-	 * @throws OCSException
622
-	 */
623
-	public function getUsersGroups(string $userId): DataResponse {
624
-		$loggedInUser = $this->userSession->getUser();
625
-
626
-		$targetUser = $this->userManager->get($userId);
627
-		if ($targetUser === null) {
628
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
629
-		}
630
-
631
-		if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
632
-			// Self lookup or admin lookup
633
-			return new DataResponse([
634
-				'groups' => $this->groupManager->getUserGroupIds($targetUser)
635
-			]);
636
-		} else {
637
-			$subAdminManager = $this->groupManager->getSubAdmin();
638
-
639
-			// Looking up someone else
640
-			if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
641
-				// Return the group that the method caller is subadmin of for the user in question
642
-				/** @var IGroup[] $getSubAdminsGroups */
643
-				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
644
-				foreach ($getSubAdminsGroups as $key => $group) {
645
-					$getSubAdminsGroups[$key] = $group->getGID();
646
-				}
647
-				$groups = array_intersect(
648
-					$getSubAdminsGroups,
649
-					$this->groupManager->getUserGroupIds($targetUser)
650
-				);
651
-				return new DataResponse(['groups' => $groups]);
652
-			} else {
653
-				// Not permitted
654
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
655
-			}
656
-		}
657
-
658
-	}
659
-
660
-	/**
661
-	 * @PasswordConfirmationRequired
662
-	 * @NoAdminRequired
663
-	 *
664
-	 * @param string $userId
665
-	 * @param string $groupid
666
-	 * @return DataResponse
667
-	 * @throws OCSException
668
-	 */
669
-	public function addToGroup(string $userId, string $groupid = ''): DataResponse {
670
-		if ($groupid === '') {
671
-			throw new OCSException('', 101);
672
-		}
673
-
674
-		$group = $this->groupManager->get($groupid);
675
-		$targetUser = $this->userManager->get($userId);
676
-		if ($group === null) {
677
-			throw new OCSException('', 102);
678
-		}
679
-		if ($targetUser === null) {
680
-			throw new OCSException('', 103);
681
-		}
682
-
683
-		// If they're not an admin, check they are a subadmin of the group in question
684
-		$loggedInUser = $this->userSession->getUser();
685
-		$subAdminManager = $this->groupManager->getSubAdmin();
686
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
687
-			throw new OCSException('', 104);
688
-		}
689
-
690
-		// Add user to group
691
-		$group->addUser($targetUser);
692
-		return new DataResponse();
693
-	}
694
-
695
-	/**
696
-	 * @PasswordConfirmationRequired
697
-	 * @NoAdminRequired
698
-	 *
699
-	 * @param string $userId
700
-	 * @param string $groupid
701
-	 * @return DataResponse
702
-	 * @throws OCSException
703
-	 */
704
-	public function removeFromGroup(string $userId, string $groupid): DataResponse {
705
-		$loggedInUser = $this->userSession->getUser();
706
-
707
-		if ($groupid === null || trim($groupid) === '') {
708
-			throw new OCSException('', 101);
709
-		}
710
-
711
-		$group = $this->groupManager->get($groupid);
712
-		if ($group === null) {
713
-			throw new OCSException('', 102);
714
-		}
715
-
716
-		$targetUser = $this->userManager->get($userId);
717
-		if ($targetUser === null) {
718
-			throw new OCSException('', 103);
719
-		}
720
-
721
-		// If they're not an admin, check they are a subadmin of the group in question
722
-		$subAdminManager = $this->groupManager->getSubAdmin();
723
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
724
-			throw new OCSException('', 104);
725
-		}
726
-
727
-		// Check they aren't removing themselves from 'admin' or their 'subadmin; group
728
-		if ($targetUser->getUID() === $loggedInUser->getUID()) {
729
-			if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
730
-				if ($group->getGID() === 'admin') {
731
-					throw new OCSException('Cannot remove yourself from the admin group', 105);
732
-				}
733
-			} else {
734
-				// Not an admin, so the user must be a subadmin of this group, but that is not allowed.
735
-				throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
736
-			}
737
-
738
-		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
739
-			/** @var IGroup[] $subAdminGroups */
740
-			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
741
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
742
-				return $subAdminGroup->getGID();
743
-			}, $subAdminGroups);
744
-			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
745
-			$userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
746
-
747
-			if (count($userSubAdminGroups) <= 1) {
748
-				// Subadmin must not be able to remove a user from all their subadmin groups.
749
-				throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
750
-			}
751
-		}
752
-
753
-		// Remove user from group
754
-		$group->removeUser($targetUser);
755
-		return new DataResponse();
756
-	}
757
-
758
-	/**
759
-	 * Creates a subadmin
760
-	 *
761
-	 * @PasswordConfirmationRequired
762
-	 *
763
-	 * @param string $userId
764
-	 * @param string $groupid
765
-	 * @return DataResponse
766
-	 * @throws OCSException
767
-	 */
768
-	public function addSubAdmin(string $userId, string $groupid): DataResponse {
769
-		$group = $this->groupManager->get($groupid);
770
-		$user = $this->userManager->get($userId);
771
-
772
-		// Check if the user exists
773
-		if ($user === null) {
774
-			throw new OCSException('User does not exist', 101);
775
-		}
776
-		// Check if group exists
777
-		if ($group === null) {
778
-			throw new OCSException('Group does not exist',  102);
779
-		}
780
-		// Check if trying to make subadmin of admin group
781
-		if ($group->getGID() === 'admin') {
782
-			throw new OCSException('Cannot create subadmins for admin group', 103);
783
-		}
784
-
785
-		$subAdminManager = $this->groupManager->getSubAdmin();
786
-
787
-		// We cannot be subadmin twice
788
-		if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
789
-			return new DataResponse();
790
-		}
791
-		// Go
792
-		if ($subAdminManager->createSubAdmin($user, $group)) {
793
-			return new DataResponse();
794
-		} else {
795
-			throw new OCSException('Unknown error occurred', 103);
796
-		}
797
-	}
798
-
799
-	/**
800
-	 * Removes a subadmin from a group
801
-	 *
802
-	 * @PasswordConfirmationRequired
803
-	 *
804
-	 * @param string $userId
805
-	 * @param string $groupid
806
-	 * @return DataResponse
807
-	 * @throws OCSException
808
-	 */
809
-	public function removeSubAdmin(string $userId, string $groupid): DataResponse {
810
-		$group = $this->groupManager->get($groupid);
811
-		$user = $this->userManager->get($userId);
812
-		$subAdminManager = $this->groupManager->getSubAdmin();
813
-
814
-		// Check if the user exists
815
-		if ($user === null) {
816
-			throw new OCSException('User does not exist', 101);
817
-		}
818
-		// Check if the group exists
819
-		if ($group === null) {
820
-			throw new OCSException('Group does not exist', 101);
821
-		}
822
-		// Check if they are a subadmin of this said group
823
-		if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
824
-			throw new OCSException('User is not a subadmin of this group', 102);
825
-		}
826
-
827
-		// Go
828
-		if ($subAdminManager->deleteSubAdmin($user, $group)) {
829
-			return new DataResponse();
830
-		} else {
831
-			throw new OCSException('Unknown error occurred', 103);
832
-		}
833
-	}
834
-
835
-	/**
836
-	 * Get the groups a user is a subadmin of
837
-	 *
838
-	 * @param string $userId
839
-	 * @return DataResponse
840
-	 * @throws OCSException
841
-	 */
842
-	public function getUserSubAdminGroups(string $userId): DataResponse {
843
-		$groups = $this->getUserSubAdminGroupsData($userId);
844
-		return new DataResponse($groups);
845
-	}
846
-
847
-	/**
848
-	 * @NoAdminRequired
849
-	 * @PasswordConfirmationRequired
850
-	 *
851
-	 * resend welcome message
852
-	 *
853
-	 * @param string $userId
854
-	 * @return DataResponse
855
-	 * @throws OCSException
856
-	 */
857
-	public function resendWelcomeMessage(string $userId): DataResponse {
858
-		$currentLoggedInUser = $this->userSession->getUser();
859
-
860
-		$targetUser = $this->userManager->get($userId);
861
-		if ($targetUser === null) {
862
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
863
-		}
864
-
865
-		// Check if admin / subadmin
866
-		$subAdminManager = $this->groupManager->getSubAdmin();
867
-		if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
868
-			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
869
-			// No rights
870
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
871
-		}
872
-
873
-		$email = $targetUser->getEMailAddress();
874
-		if ($email === '' || $email === null) {
875
-			throw new OCSException('Email address not available', 101);
876
-		}
877
-		$username = $targetUser->getUID();
878
-		$lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
879
-		if (!$this->l10nFactory->languageExists('settings', $lang)) {
880
-			$lang = 'en';
881
-		}
882
-
883
-		$l10n = $this->l10nFactory->get('settings', $lang);
884
-
885
-		try {
886
-			$this->newUserMailHelper->setL10N($l10n);
887
-			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
888
-			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
889
-		} catch(\Exception $e) {
890
-			$this->logger->logException($e, [
891
-				'message' => "Can't send new user mail to $email",
892
-				'level' => ILogger::ERROR,
893
-				'app' => 'settings',
894
-			]);
895
-			throw new OCSException('Sending email failed', 102);
896
-		}
897
-
898
-		return new DataResponse();
899
-	}
55
+    /** @var IAppManager */
56
+    private $appManager;
57
+    /** @var ILogger */
58
+    private $logger;
59
+    /** @var IFactory */
60
+    private $l10nFactory;
61
+    /** @var NewUserMailHelper */
62
+    private $newUserMailHelper;
63
+    /** @var FederatedFileSharingFactory */
64
+    private $federatedFileSharingFactory;
65
+    /** @var ISecureRandom */
66
+    private $secureRandom;
67
+
68
+    /**
69
+     * @param string $appName
70
+     * @param IRequest $request
71
+     * @param IUserManager $userManager
72
+     * @param IConfig $config
73
+     * @param IAppManager $appManager
74
+     * @param IGroupManager $groupManager
75
+     * @param IUserSession $userSession
76
+     * @param AccountManager $accountManager
77
+     * @param ILogger $logger
78
+     * @param IFactory $l10nFactory
79
+     * @param NewUserMailHelper $newUserMailHelper
80
+     * @param FederatedFileSharingFactory $federatedFileSharingFactory
81
+     * @param ISecureRandom $secureRandom
82
+     */
83
+    public function __construct(string $appName,
84
+                                IRequest $request,
85
+                                IUserManager $userManager,
86
+                                IConfig $config,
87
+                                IAppManager $appManager,
88
+                                IGroupManager $groupManager,
89
+                                IUserSession $userSession,
90
+                                AccountManager $accountManager,
91
+                                ILogger $logger,
92
+                                IFactory $l10nFactory,
93
+                                NewUserMailHelper $newUserMailHelper,
94
+                                FederatedFileSharingFactory $federatedFileSharingFactory,
95
+                                ISecureRandom $secureRandom) {
96
+        parent::__construct($appName,
97
+                            $request,
98
+                            $userManager,
99
+                            $config,
100
+                            $groupManager,
101
+                            $userSession,
102
+                            $accountManager);
103
+
104
+        $this->appManager = $appManager;
105
+        $this->logger = $logger;
106
+        $this->l10nFactory = $l10nFactory;
107
+        $this->newUserMailHelper = $newUserMailHelper;
108
+        $this->federatedFileSharingFactory = $federatedFileSharingFactory;
109
+        $this->secureRandom = $secureRandom;
110
+    }
111
+
112
+    /**
113
+     * @NoAdminRequired
114
+     *
115
+     * returns a list of users
116
+     *
117
+     * @param string $search
118
+     * @param int $limit
119
+     * @param int $offset
120
+     * @return DataResponse
121
+     */
122
+    public function getUsers(string $search = '', $limit = null, $offset = 0): DataResponse {
123
+        $user = $this->userSession->getUser();
124
+        $users = [];
125
+
126
+        // Admin? Or SubAdmin?
127
+        $uid = $user->getUID();
128
+        $subAdminManager = $this->groupManager->getSubAdmin();
129
+        if ($this->groupManager->isAdmin($uid)){
130
+            $users = $this->userManager->search($search, $limit, $offset);
131
+        } else if ($subAdminManager->isSubAdmin($user)) {
132
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
133
+            foreach ($subAdminOfGroups as $key => $group) {
134
+                $subAdminOfGroups[$key] = $group->getGID();
135
+            }
136
+
137
+            $users = [];
138
+            foreach ($subAdminOfGroups as $group) {
139
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
140
+            }
141
+        }
142
+
143
+        $users = array_keys($users);
144
+
145
+        return new DataResponse([
146
+            'users' => $users
147
+        ]);
148
+    }
149
+
150
+    /**
151
+     * @NoAdminRequired
152
+     *
153
+     * returns a list of users and their data
154
+     */
155
+    public function getUsersDetails(string $search = '', $limit = null, $offset = 0): DataResponse {
156
+        $user = $this->userSession->getUser();
157
+        $users = [];
158
+
159
+        // Admin? Or SubAdmin?
160
+        $uid = $user->getUID();
161
+        $subAdminManager = $this->groupManager->getSubAdmin();
162
+        if ($this->groupManager->isAdmin($uid)){
163
+            $users = $this->userManager->search($search, $limit, $offset);
164
+        } else if ($subAdminManager->isSubAdmin($user)) {
165
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
166
+            foreach ($subAdminOfGroups as $key => $group) {
167
+                $subAdminOfGroups[$key] = $group->getGID();
168
+            }
169
+
170
+            $users = [];
171
+            foreach ($subAdminOfGroups as $group) {
172
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
173
+            }
174
+        }
175
+
176
+        $users = array_keys($users);
177
+        $usersDetails = [];
178
+        foreach ($users as $key => $userId) {
179
+            $userData = $this->getUserData($userId);
180
+            // Do not insert empty entry
181
+            if (!empty($userData)) {
182
+                $usersDetails[$userId] = $userData;
183
+            } else {
184
+                // Logged user does not have permissions to see this user
185
+                // only showing its id
186
+                $usersDetails[$userId] = ['id' => $userId];
187
+            }
188
+        }
189
+
190
+        return new DataResponse([
191
+            'users' => $usersDetails
192
+        ]);
193
+    }
194
+
195
+    /**
196
+     * @PasswordConfirmationRequired
197
+     * @NoAdminRequired
198
+     *
199
+     * @param string $userid
200
+     * @param string $password
201
+     * @param string $email
202
+     * @param array $groups
203
+     * @param array $subadmins
204
+     * @param string $quota
205
+     * @param string $language
206
+     * @return DataResponse
207
+     * @throws OCSException
208
+     */
209
+    public function addUser(string $userid,
210
+                            string $password = '',
211
+                            string $email = '',
212
+                            array $groups = [],
213
+                            array $subadmin = [],
214
+                            string $quota = '',
215
+                            string $language = ''): DataResponse {
216
+        $user = $this->userSession->getUser();
217
+        $isAdmin = $this->groupManager->isAdmin($user->getUID());
218
+        $subAdminManager = $this->groupManager->getSubAdmin();
219
+
220
+        if ($this->userManager->userExists($userid)) {
221
+            $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
222
+            throw new OCSException('User already exists', 102);
223
+        }
224
+
225
+        if ($groups !== []) {
226
+            foreach ($groups as $group) {
227
+                if (!$this->groupManager->groupExists($group)) {
228
+                    throw new OCSException('group '.$group.' does not exist', 104);
229
+                }
230
+                if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
231
+                    throw new OCSException('insufficient privileges for group '. $group, 105);
232
+                }
233
+            }
234
+        } else {
235
+            if (!$isAdmin) {
236
+                throw new OCSException('no group specified (required for subadmins)', 106);
237
+            }
238
+        }
239
+
240
+        $subadminGroups = [];
241
+        if ($subadmin !== []) {
242
+            foreach ($subadmin as $groupid) {
243
+                $group = $this->groupManager->get($groupid);
244
+                // Check if group exists
245
+                if ($group === null) {
246
+                    throw new OCSException('Subadmin group does not exist',  102);
247
+                }
248
+                // Check if trying to make subadmin of admin group
249
+                if ($group->getGID() === 'admin') {
250
+                    throw new OCSException('Cannot create subadmins for admin group', 103);
251
+                }
252
+                // Check if has permission to promote subadmins
253
+                if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) {
254
+                    throw new OCSForbiddenException('No permissions to promote subadmins');
255
+                }
256
+                $subadminGroups[] = $group;
257
+            }
258
+        }
259
+
260
+        $generatePasswordResetToken = false;
261
+        if ($password === '') {
262
+            if ($email === '') {
263
+                throw new OCSException('To send a password link to the user an email address is required.', 108);
264
+            }
265
+
266
+            $password = $this->secureRandom->generate(10);
267
+            // Make sure we pass the password_policy
268
+            $password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
269
+            $generatePasswordResetToken = true;
270
+        }
271
+
272
+        try {
273
+            $newUser = $this->userManager->createUser($userid, $password);
274
+            $this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
275
+
276
+            foreach ($groups as $group) {
277
+                $this->groupManager->get($group)->addUser($newUser);
278
+                $this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
279
+            }
280
+            foreach ($subadminGroups as $group) {
281
+                $subAdminManager->createSubAdmin($newUser, $group);
282
+            }
283
+
284
+            if ($quota !== '') {
285
+                $this->editUser($userid, 'quota', $quota);
286
+            }
287
+
288
+            if ($language !== '') {
289
+                $this->editUser($userid, 'language', $language);
290
+            }
291
+
292
+            // Send new user mail only if a mail is set
293
+            if ($email !== '') {
294
+                $newUser->setEMailAddress($email);
295
+                try {
296
+                    $emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
297
+                    $this->newUserMailHelper->sendMail($newUser, $emailTemplate);
298
+                } catch (\Exception $e) {
299
+                    $this->logger->logException($e, [
300
+                        'message' => "Can't send new user mail to $email",
301
+                        'level' => ILogger::ERROR,
302
+                        'app' => 'ocs_api',
303
+                    ]);
304
+                    throw new OCSException('Unable to send the invitation mail', 109);
305
+                }
306
+            }
307
+
308
+            return new DataResponse();
309
+
310
+        } catch (HintException $e ) {
311
+            $this->logger->logException($e, [
312
+                'message' => 'Failed addUser attempt with hint exception.',
313
+                'level' => ILogger::WARN,
314
+                'app' => 'ocs_api',
315
+            ]);
316
+            throw new OCSException($e->getHint(), 107);
317
+        } catch (\Exception $e) {
318
+            $this->logger->logException($e, [
319
+                'message' => 'Failed addUser attempt with exception.',
320
+                'level' => ILogger::ERROR,
321
+                'app' => 'ocs_api',
322
+            ]);
323
+            throw new OCSException('Bad request', 101);
324
+        }
325
+    }
326
+
327
+    /**
328
+     * @NoAdminRequired
329
+     * @NoSubAdminRequired
330
+     *
331
+     * gets user info
332
+     *
333
+     * @param string $userId
334
+     * @return DataResponse
335
+     * @throws OCSException
336
+     */
337
+    public function getUser(string $userId): DataResponse {
338
+        $data = $this->getUserData($userId);
339
+        // getUserData returns empty array if not enough permissions
340
+        if (empty($data)) {
341
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
342
+        }
343
+        return new DataResponse($data);
344
+    }
345
+
346
+    /**
347
+     * @NoAdminRequired
348
+     * @NoSubAdminRequired
349
+     *
350
+     * gets user info from the currently logged in user
351
+     *
352
+     * @return DataResponse
353
+     * @throws OCSException
354
+     */
355
+    public function getCurrentUser(): DataResponse {
356
+        $user = $this->userSession->getUser();
357
+        if ($user) {
358
+            $data =  $this->getUserData($user->getUID());
359
+            // rename "displayname" to "display-name" only for this call to keep
360
+            // the API stable.
361
+            $data['display-name'] = $data['displayname'];
362
+            unset($data['displayname']);
363
+            return new DataResponse($data);
364
+
365
+        }
366
+
367
+        throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
368
+    }
369
+
370
+    /**
371
+     * @NoAdminRequired
372
+     * @NoSubAdminRequired
373
+     */
374
+    public function getEditableFields(): DataResponse {
375
+        $permittedFields = [];
376
+
377
+        // Editing self (display, email)
378
+        if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
379
+            $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
380
+            $permittedFields[] = AccountManager::PROPERTY_EMAIL;
381
+        }
382
+
383
+        if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
384
+            $federatedFileSharing = $this->federatedFileSharingFactory->get();
385
+            $shareProvider = $federatedFileSharing->getFederatedShareProvider();
386
+            if ($shareProvider->isLookupServerUploadEnabled()) {
387
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
388
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
389
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
390
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
391
+            }
392
+        }
393
+
394
+        return new DataResponse($permittedFields);
395
+    }
396
+
397
+    /**
398
+     * @NoAdminRequired
399
+     * @NoSubAdminRequired
400
+     * @PasswordConfirmationRequired
401
+     *
402
+     * edit users
403
+     *
404
+     * @param string $userId
405
+     * @param string $key
406
+     * @param string $value
407
+     * @return DataResponse
408
+     * @throws OCSException
409
+     */
410
+    public function editUser(string $userId, string $key, string $value): DataResponse {
411
+        $currentLoggedInUser = $this->userSession->getUser();
412
+
413
+        $targetUser = $this->userManager->get($userId);
414
+        if ($targetUser === null) {
415
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
416
+        }
417
+
418
+        $permittedFields = [];
419
+        if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
420
+            // Editing self (display, email)
421
+            if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
422
+                $permittedFields[] = 'display';
423
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
424
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
425
+            }
426
+
427
+            $permittedFields[] = 'password';
428
+            if ($this->config->getSystemValue('force_language', false) === false ||
429
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
430
+                $permittedFields[] = 'language';
431
+            }
432
+
433
+            if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
434
+                $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
435
+                $shareProvider = $federatedFileSharing->getFederatedShareProvider();
436
+                if ($shareProvider->isLookupServerUploadEnabled()) {
437
+                    $permittedFields[] = AccountManager::PROPERTY_PHONE;
438
+                    $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
439
+                    $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
440
+                    $permittedFields[] = AccountManager::PROPERTY_TWITTER;
441
+                }
442
+            }
443
+
444
+            // If admin they can edit their own quota
445
+            if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
446
+                $permittedFields[] = 'quota';
447
+            }
448
+        } else {
449
+            // Check if admin / subadmin
450
+            $subAdminManager = $this->groupManager->getSubAdmin();
451
+            if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
452
+            || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
453
+                // They have permissions over the user
454
+                $permittedFields[] = 'display';
455
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
456
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
457
+                $permittedFields[] = 'password';
458
+                $permittedFields[] = 'language';
459
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
460
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
461
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
462
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
463
+                $permittedFields[] = 'quota';
464
+            } else {
465
+                // No rights
466
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
467
+            }
468
+        }
469
+        // Check if permitted to edit this field
470
+        if (!in_array($key, $permittedFields)) {
471
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
472
+        }
473
+        // Process the edit
474
+        switch($key) {
475
+            case 'display':
476
+            case AccountManager::PROPERTY_DISPLAYNAME:
477
+                $targetUser->setDisplayName($value);
478
+                break;
479
+            case 'quota':
480
+                $quota = $value;
481
+                if ($quota !== 'none' && $quota !== 'default') {
482
+                    if (is_numeric($quota)) {
483
+                        $quota = (float) $quota;
484
+                    } else {
485
+                        $quota = \OCP\Util::computerFileSize($quota);
486
+                    }
487
+                    if ($quota === false) {
488
+                        throw new OCSException('Invalid quota value '.$value, 103);
489
+                    }
490
+                    if ($quota === 0) {
491
+                        $quota = 'default';
492
+                    }else if ($quota === -1) {
493
+                        $quota = 'none';
494
+                    } else {
495
+                        $quota = \OCP\Util::humanFileSize($quota);
496
+                    }
497
+                }
498
+                $targetUser->setQuota($quota);
499
+                break;
500
+            case 'password':
501
+                $targetUser->setPassword($value);
502
+                break;
503
+            case 'language':
504
+                $languagesCodes = $this->l10nFactory->findAvailableLanguages();
505
+                if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
506
+                    throw new OCSException('Invalid language', 102);
507
+                }
508
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
509
+                break;
510
+            case AccountManager::PROPERTY_EMAIL:
511
+                if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
512
+                    $targetUser->setEMailAddress($value);
513
+                } else {
514
+                    throw new OCSException('', 102);
515
+                }
516
+                break;
517
+            case AccountManager::PROPERTY_PHONE:
518
+            case AccountManager::PROPERTY_ADDRESS:
519
+            case AccountManager::PROPERTY_WEBSITE:
520
+            case AccountManager::PROPERTY_TWITTER:
521
+                $userAccount = $this->accountManager->getUser($targetUser);
522
+                if ($userAccount[$key]['value'] !== $value) {
523
+                    $userAccount[$key]['value'] = $value;
524
+                    $this->accountManager->updateUser($targetUser, $userAccount);
525
+                }
526
+                break;
527
+            default:
528
+                throw new OCSException('', 103);
529
+        }
530
+        return new DataResponse();
531
+    }
532
+
533
+    /**
534
+     * @PasswordConfirmationRequired
535
+     * @NoAdminRequired
536
+     *
537
+     * @param string $userId
538
+     * @return DataResponse
539
+     * @throws OCSException
540
+     */
541
+    public function deleteUser(string $userId): DataResponse {
542
+        $currentLoggedInUser = $this->userSession->getUser();
543
+
544
+        $targetUser = $this->userManager->get($userId);
545
+
546
+        if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
547
+            throw new OCSException('', 101);
548
+        }
549
+
550
+        // If not permitted
551
+        $subAdminManager = $this->groupManager->getSubAdmin();
552
+        if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
553
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
554
+        }
555
+
556
+        // Go ahead with the delete
557
+        if ($targetUser->delete()) {
558
+            return new DataResponse();
559
+        } else {
560
+            throw new OCSException('', 101);
561
+        }
562
+    }
563
+
564
+    /**
565
+     * @PasswordConfirmationRequired
566
+     * @NoAdminRequired
567
+     *
568
+     * @param string $userId
569
+     * @return DataResponse
570
+     * @throws OCSException
571
+     * @throws OCSForbiddenException
572
+     */
573
+    public function disableUser(string $userId): DataResponse {
574
+        return $this->setEnabled($userId, false);
575
+    }
576
+
577
+    /**
578
+     * @PasswordConfirmationRequired
579
+     * @NoAdminRequired
580
+     *
581
+     * @param string $userId
582
+     * @return DataResponse
583
+     * @throws OCSException
584
+     * @throws OCSForbiddenException
585
+     */
586
+    public function enableUser(string $userId): DataResponse {
587
+        return $this->setEnabled($userId, true);
588
+    }
589
+
590
+    /**
591
+     * @param string $userId
592
+     * @param bool $value
593
+     * @return DataResponse
594
+     * @throws OCSException
595
+     */
596
+    private function setEnabled(string $userId, bool $value): DataResponse {
597
+        $currentLoggedInUser = $this->userSession->getUser();
598
+
599
+        $targetUser = $this->userManager->get($userId);
600
+        if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
601
+            throw new OCSException('', 101);
602
+        }
603
+
604
+        // If not permitted
605
+        $subAdminManager = $this->groupManager->getSubAdmin();
606
+        if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
607
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
608
+        }
609
+
610
+        // enable/disable the user now
611
+        $targetUser->setEnabled($value);
612
+        return new DataResponse();
613
+    }
614
+
615
+    /**
616
+     * @NoAdminRequired
617
+     * @NoSubAdminRequired
618
+     *
619
+     * @param string $userId
620
+     * @return DataResponse
621
+     * @throws OCSException
622
+     */
623
+    public function getUsersGroups(string $userId): DataResponse {
624
+        $loggedInUser = $this->userSession->getUser();
625
+
626
+        $targetUser = $this->userManager->get($userId);
627
+        if ($targetUser === null) {
628
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
629
+        }
630
+
631
+        if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
632
+            // Self lookup or admin lookup
633
+            return new DataResponse([
634
+                'groups' => $this->groupManager->getUserGroupIds($targetUser)
635
+            ]);
636
+        } else {
637
+            $subAdminManager = $this->groupManager->getSubAdmin();
638
+
639
+            // Looking up someone else
640
+            if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
641
+                // Return the group that the method caller is subadmin of for the user in question
642
+                /** @var IGroup[] $getSubAdminsGroups */
643
+                $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
644
+                foreach ($getSubAdminsGroups as $key => $group) {
645
+                    $getSubAdminsGroups[$key] = $group->getGID();
646
+                }
647
+                $groups = array_intersect(
648
+                    $getSubAdminsGroups,
649
+                    $this->groupManager->getUserGroupIds($targetUser)
650
+                );
651
+                return new DataResponse(['groups' => $groups]);
652
+            } else {
653
+                // Not permitted
654
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
655
+            }
656
+        }
657
+
658
+    }
659
+
660
+    /**
661
+     * @PasswordConfirmationRequired
662
+     * @NoAdminRequired
663
+     *
664
+     * @param string $userId
665
+     * @param string $groupid
666
+     * @return DataResponse
667
+     * @throws OCSException
668
+     */
669
+    public function addToGroup(string $userId, string $groupid = ''): DataResponse {
670
+        if ($groupid === '') {
671
+            throw new OCSException('', 101);
672
+        }
673
+
674
+        $group = $this->groupManager->get($groupid);
675
+        $targetUser = $this->userManager->get($userId);
676
+        if ($group === null) {
677
+            throw new OCSException('', 102);
678
+        }
679
+        if ($targetUser === null) {
680
+            throw new OCSException('', 103);
681
+        }
682
+
683
+        // If they're not an admin, check they are a subadmin of the group in question
684
+        $loggedInUser = $this->userSession->getUser();
685
+        $subAdminManager = $this->groupManager->getSubAdmin();
686
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
687
+            throw new OCSException('', 104);
688
+        }
689
+
690
+        // Add user to group
691
+        $group->addUser($targetUser);
692
+        return new DataResponse();
693
+    }
694
+
695
+    /**
696
+     * @PasswordConfirmationRequired
697
+     * @NoAdminRequired
698
+     *
699
+     * @param string $userId
700
+     * @param string $groupid
701
+     * @return DataResponse
702
+     * @throws OCSException
703
+     */
704
+    public function removeFromGroup(string $userId, string $groupid): DataResponse {
705
+        $loggedInUser = $this->userSession->getUser();
706
+
707
+        if ($groupid === null || trim($groupid) === '') {
708
+            throw new OCSException('', 101);
709
+        }
710
+
711
+        $group = $this->groupManager->get($groupid);
712
+        if ($group === null) {
713
+            throw new OCSException('', 102);
714
+        }
715
+
716
+        $targetUser = $this->userManager->get($userId);
717
+        if ($targetUser === null) {
718
+            throw new OCSException('', 103);
719
+        }
720
+
721
+        // If they're not an admin, check they are a subadmin of the group in question
722
+        $subAdminManager = $this->groupManager->getSubAdmin();
723
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
724
+            throw new OCSException('', 104);
725
+        }
726
+
727
+        // Check they aren't removing themselves from 'admin' or their 'subadmin; group
728
+        if ($targetUser->getUID() === $loggedInUser->getUID()) {
729
+            if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
730
+                if ($group->getGID() === 'admin') {
731
+                    throw new OCSException('Cannot remove yourself from the admin group', 105);
732
+                }
733
+            } else {
734
+                // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
735
+                throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
736
+            }
737
+
738
+        } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
739
+            /** @var IGroup[] $subAdminGroups */
740
+            $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
741
+            $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
742
+                return $subAdminGroup->getGID();
743
+            }, $subAdminGroups);
744
+            $userGroups = $this->groupManager->getUserGroupIds($targetUser);
745
+            $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
746
+
747
+            if (count($userSubAdminGroups) <= 1) {
748
+                // Subadmin must not be able to remove a user from all their subadmin groups.
749
+                throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
750
+            }
751
+        }
752
+
753
+        // Remove user from group
754
+        $group->removeUser($targetUser);
755
+        return new DataResponse();
756
+    }
757
+
758
+    /**
759
+     * Creates a subadmin
760
+     *
761
+     * @PasswordConfirmationRequired
762
+     *
763
+     * @param string $userId
764
+     * @param string $groupid
765
+     * @return DataResponse
766
+     * @throws OCSException
767
+     */
768
+    public function addSubAdmin(string $userId, string $groupid): DataResponse {
769
+        $group = $this->groupManager->get($groupid);
770
+        $user = $this->userManager->get($userId);
771
+
772
+        // Check if the user exists
773
+        if ($user === null) {
774
+            throw new OCSException('User does not exist', 101);
775
+        }
776
+        // Check if group exists
777
+        if ($group === null) {
778
+            throw new OCSException('Group does not exist',  102);
779
+        }
780
+        // Check if trying to make subadmin of admin group
781
+        if ($group->getGID() === 'admin') {
782
+            throw new OCSException('Cannot create subadmins for admin group', 103);
783
+        }
784
+
785
+        $subAdminManager = $this->groupManager->getSubAdmin();
786
+
787
+        // We cannot be subadmin twice
788
+        if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
789
+            return new DataResponse();
790
+        }
791
+        // Go
792
+        if ($subAdminManager->createSubAdmin($user, $group)) {
793
+            return new DataResponse();
794
+        } else {
795
+            throw new OCSException('Unknown error occurred', 103);
796
+        }
797
+    }
798
+
799
+    /**
800
+     * Removes a subadmin from a group
801
+     *
802
+     * @PasswordConfirmationRequired
803
+     *
804
+     * @param string $userId
805
+     * @param string $groupid
806
+     * @return DataResponse
807
+     * @throws OCSException
808
+     */
809
+    public function removeSubAdmin(string $userId, string $groupid): DataResponse {
810
+        $group = $this->groupManager->get($groupid);
811
+        $user = $this->userManager->get($userId);
812
+        $subAdminManager = $this->groupManager->getSubAdmin();
813
+
814
+        // Check if the user exists
815
+        if ($user === null) {
816
+            throw new OCSException('User does not exist', 101);
817
+        }
818
+        // Check if the group exists
819
+        if ($group === null) {
820
+            throw new OCSException('Group does not exist', 101);
821
+        }
822
+        // Check if they are a subadmin of this said group
823
+        if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
824
+            throw new OCSException('User is not a subadmin of this group', 102);
825
+        }
826
+
827
+        // Go
828
+        if ($subAdminManager->deleteSubAdmin($user, $group)) {
829
+            return new DataResponse();
830
+        } else {
831
+            throw new OCSException('Unknown error occurred', 103);
832
+        }
833
+    }
834
+
835
+    /**
836
+     * Get the groups a user is a subadmin of
837
+     *
838
+     * @param string $userId
839
+     * @return DataResponse
840
+     * @throws OCSException
841
+     */
842
+    public function getUserSubAdminGroups(string $userId): DataResponse {
843
+        $groups = $this->getUserSubAdminGroupsData($userId);
844
+        return new DataResponse($groups);
845
+    }
846
+
847
+    /**
848
+     * @NoAdminRequired
849
+     * @PasswordConfirmationRequired
850
+     *
851
+     * resend welcome message
852
+     *
853
+     * @param string $userId
854
+     * @return DataResponse
855
+     * @throws OCSException
856
+     */
857
+    public function resendWelcomeMessage(string $userId): DataResponse {
858
+        $currentLoggedInUser = $this->userSession->getUser();
859
+
860
+        $targetUser = $this->userManager->get($userId);
861
+        if ($targetUser === null) {
862
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
863
+        }
864
+
865
+        // Check if admin / subadmin
866
+        $subAdminManager = $this->groupManager->getSubAdmin();
867
+        if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
868
+            && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
869
+            // No rights
870
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
871
+        }
872
+
873
+        $email = $targetUser->getEMailAddress();
874
+        if ($email === '' || $email === null) {
875
+            throw new OCSException('Email address not available', 101);
876
+        }
877
+        $username = $targetUser->getUID();
878
+        $lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
879
+        if (!$this->l10nFactory->languageExists('settings', $lang)) {
880
+            $lang = 'en';
881
+        }
882
+
883
+        $l10n = $this->l10nFactory->get('settings', $lang);
884
+
885
+        try {
886
+            $this->newUserMailHelper->setL10N($l10n);
887
+            $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
888
+            $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
889
+        } catch(\Exception $e) {
890
+            $this->logger->logException($e, [
891
+                'message' => "Can't send new user mail to $email",
892
+                'level' => ILogger::ERROR,
893
+                'app' => 'settings',
894
+            ]);
895
+            throw new OCSException('Sending email failed', 102);
896
+        }
897
+
898
+        return new DataResponse();
899
+    }
900 900
 }
Please login to merge, or discard this patch.
apps/provisioning_api/lib/Controller/GroupsController.php 1 patch
Indentation   +218 added lines, -218 removed lines patch added patch discarded remove patch
@@ -44,244 +44,244 @@
 block discarded – undo
44 44
 
45 45
 class GroupsController extends AUserData {
46 46
 
47
-	/** @var ILogger */
48
-	private $logger;
47
+    /** @var ILogger */
48
+    private $logger;
49 49
 
50
-	/**
51
-	 * @param string $appName
52
-	 * @param IRequest $request
53
-	 * @param IUserManager $userManager
54
-	 * @param IConfig $config
55
-	 * @param IGroupManager $groupManager
56
-	 * @param IUserSession $userSession
57
-	 * @param AccountManager $accountManager
58
-	 * @param ILogger $logger
59
-	 * @param UsersController $userController
60
-	 */
61
-	public function __construct(string $appName,
62
-								IRequest $request,
63
-								IUserManager $userManager,
64
-								IConfig $config,
65
-								IGroupManager $groupManager,
66
-								IUserSession $userSession,
67
-								AccountManager $accountManager,
68
-								ILogger $logger) {
69
-		parent::__construct($appName,
70
-			$request,
71
-			$userManager,
72
-			$config,
73
-			$groupManager,
74
-			$userSession,
75
-			$accountManager);
50
+    /**
51
+     * @param string $appName
52
+     * @param IRequest $request
53
+     * @param IUserManager $userManager
54
+     * @param IConfig $config
55
+     * @param IGroupManager $groupManager
56
+     * @param IUserSession $userSession
57
+     * @param AccountManager $accountManager
58
+     * @param ILogger $logger
59
+     * @param UsersController $userController
60
+     */
61
+    public function __construct(string $appName,
62
+                                IRequest $request,
63
+                                IUserManager $userManager,
64
+                                IConfig $config,
65
+                                IGroupManager $groupManager,
66
+                                IUserSession $userSession,
67
+                                AccountManager $accountManager,
68
+                                ILogger $logger) {
69
+        parent::__construct($appName,
70
+            $request,
71
+            $userManager,
72
+            $config,
73
+            $groupManager,
74
+            $userSession,
75
+            $accountManager);
76 76
 
77
-		$this->logger = $logger;
78
-	}
77
+        $this->logger = $logger;
78
+    }
79 79
 
80
-	/**
81
-	 * returns a list of groups
82
-	 *
83
-	 * @NoAdminRequired
84
-	 *
85
-	 * @param string $search
86
-	 * @param int $limit
87
-	 * @param int $offset
88
-	 * @return DataResponse
89
-	 */
90
-	public function getGroups(string $search = '', int $limit = null, int $offset = 0): DataResponse {
91
-		$groups = $this->groupManager->search($search, $limit, $offset);
92
-		$groups = array_map(function($group) {
93
-			/** @var IGroup $group */
94
-			return $group->getGID();
95
-		}, $groups);
80
+    /**
81
+     * returns a list of groups
82
+     *
83
+     * @NoAdminRequired
84
+     *
85
+     * @param string $search
86
+     * @param int $limit
87
+     * @param int $offset
88
+     * @return DataResponse
89
+     */
90
+    public function getGroups(string $search = '', int $limit = null, int $offset = 0): DataResponse {
91
+        $groups = $this->groupManager->search($search, $limit, $offset);
92
+        $groups = array_map(function($group) {
93
+            /** @var IGroup $group */
94
+            return $group->getGID();
95
+        }, $groups);
96 96
 
97
-		return new DataResponse(['groups' => $groups]);
98
-	}
97
+        return new DataResponse(['groups' => $groups]);
98
+    }
99 99
 
100
-	/**
101
-	 * returns a list of groups details with ids and displaynames
102
-	 *
103
-	 * @NoAdminRequired
104
-	 *
105
-	 * @param string $search
106
-	 * @param int $limit
107
-	 * @param int $offset
108
-	 * @return DataResponse
109
-	 */
110
-	public function getGroupsDetails(string $search = '', int $limit = null, int $offset = 0): DataResponse {
111
-		$groups = $this->groupManager->search($search, $limit, $offset);
112
-		$groups = array_map(function($group) {
113
-			/** @var IGroup $group */
114
-			return [
115
-				'id' => $group->getGID(),
116
-				'displayname' => $group->getDisplayName(),
117
-				'usercount' => $group->count(),
118
-				'disabled' => $group->countDisabled()
119
-			];
120
-		}, $groups);
100
+    /**
101
+     * returns a list of groups details with ids and displaynames
102
+     *
103
+     * @NoAdminRequired
104
+     *
105
+     * @param string $search
106
+     * @param int $limit
107
+     * @param int $offset
108
+     * @return DataResponse
109
+     */
110
+    public function getGroupsDetails(string $search = '', int $limit = null, int $offset = 0): DataResponse {
111
+        $groups = $this->groupManager->search($search, $limit, $offset);
112
+        $groups = array_map(function($group) {
113
+            /** @var IGroup $group */
114
+            return [
115
+                'id' => $group->getGID(),
116
+                'displayname' => $group->getDisplayName(),
117
+                'usercount' => $group->count(),
118
+                'disabled' => $group->countDisabled()
119
+            ];
120
+        }, $groups);
121 121
 
122
-		return new DataResponse(['groups' => $groups]);
123
-	}
122
+        return new DataResponse(['groups' => $groups]);
123
+    }
124 124
 
125
-	/**
126
-	 * @NoAdminRequired
127
-	 *
128
-	 * @param string $groupId
129
-	 * @return DataResponse
130
-	 * @throws OCSException	
131
-	 *
132
-	 * @deprecated 14 Use getGroupUsers
133
-	 */
134
-	public function getGroup(string $groupId): DataResponse {
135
-		return $this->getGroupUsers($groupId);
136
-	}
125
+    /**
126
+     * @NoAdminRequired
127
+     *
128
+     * @param string $groupId
129
+     * @return DataResponse
130
+     * @throws OCSException	
131
+     *
132
+     * @deprecated 14 Use getGroupUsers
133
+     */
134
+    public function getGroup(string $groupId): DataResponse {
135
+        return $this->getGroupUsers($groupId);
136
+    }
137 137
 
138
-	/**
139
-	 * returns an array of users in the specified group
140
-	 *
141
-	 * @NoAdminRequired
142
-	 *
143
-	 * @param string $groupId
144
-	 * @return DataResponse
145
-	 * @throws OCSException
146
-	 */
147
-	public function getGroupUsers(string $groupId): DataResponse {
148
-		$user = $this->userSession->getUser();
149
-		$isSubadminOfGroup = false;
138
+    /**
139
+     * returns an array of users in the specified group
140
+     *
141
+     * @NoAdminRequired
142
+     *
143
+     * @param string $groupId
144
+     * @return DataResponse
145
+     * @throws OCSException
146
+     */
147
+    public function getGroupUsers(string $groupId): DataResponse {
148
+        $user = $this->userSession->getUser();
149
+        $isSubadminOfGroup = false;
150 150
 
151
-		// Check the group exists
152
-		$group = $this->groupManager->get($groupId);
153
-		if ($group !== null) {
154
-			$isSubadminOfGroup =$this->groupManager->getSubAdmin()->isSubAdminOfGroup($user, $group);
155
-		} else {
156
-			throw new OCSNotFoundException('The requested group could not be found');
157
-		}
151
+        // Check the group exists
152
+        $group = $this->groupManager->get($groupId);
153
+        if ($group !== null) {
154
+            $isSubadminOfGroup =$this->groupManager->getSubAdmin()->isSubAdminOfGroup($user, $group);
155
+        } else {
156
+            throw new OCSNotFoundException('The requested group could not be found');
157
+        }
158 158
 
159
-		// Check subadmin has access to this group
160
-		if($this->groupManager->isAdmin($user->getUID())
161
-		   || $isSubadminOfGroup) {
162
-			$users = $this->groupManager->get($groupId)->getUsers();
163
-			$users =  array_map(function($user) {
164
-				/** @var IUser $user */
165
-				return $user->getUID();
166
-			}, $users);
167
-			$users = array_values($users);
168
-			return new DataResponse(['users' => $users]);
169
-		}
159
+        // Check subadmin has access to this group
160
+        if($this->groupManager->isAdmin($user->getUID())
161
+           || $isSubadminOfGroup) {
162
+            $users = $this->groupManager->get($groupId)->getUsers();
163
+            $users =  array_map(function($user) {
164
+                /** @var IUser $user */
165
+                return $user->getUID();
166
+            }, $users);
167
+            $users = array_values($users);
168
+            return new DataResponse(['users' => $users]);
169
+        }
170 170
 
171
-		throw new OCSForbiddenException();
172
-	}
171
+        throw new OCSForbiddenException();
172
+    }
173 173
 
174
-	/**
175
-	 * returns an array of users details in the specified group
176
-	 *
177
-	 * @NoAdminRequired
178
-	 *
179
-	 * @param string $groupId
180
-	 * @param int $limit
181
-	 * @param int $offset
182
-	 * @return DataResponse
183
-	 * @throws OCSException
184
-	 */
185
-	public function getGroupUsersDetails(string $groupId, int $limit = null, int $offset = 0): DataResponse {
186
-		$user = $this->userSession->getUser();
187
-		$isSubadminOfGroup = false;
174
+    /**
175
+     * returns an array of users details in the specified group
176
+     *
177
+     * @NoAdminRequired
178
+     *
179
+     * @param string $groupId
180
+     * @param int $limit
181
+     * @param int $offset
182
+     * @return DataResponse
183
+     * @throws OCSException
184
+     */
185
+    public function getGroupUsersDetails(string $groupId, int $limit = null, int $offset = 0): DataResponse {
186
+        $user = $this->userSession->getUser();
187
+        $isSubadminOfGroup = false;
188 188
 
189
-		// Check the group exists
190
-		$group = $this->groupManager->get($groupId);
191
-		if ($group !== null) {
192
-			$isSubadminOfGroup =$this->groupManager->getSubAdmin()->isSubAdminOfGroup($user, $group);
193
-		} else {
194
-			throw new OCSException('The requested group could not be found', \OCP\API::RESPOND_NOT_FOUND);
195
-		}
189
+        // Check the group exists
190
+        $group = $this->groupManager->get($groupId);
191
+        if ($group !== null) {
192
+            $isSubadminOfGroup =$this->groupManager->getSubAdmin()->isSubAdminOfGroup($user, $group);
193
+        } else {
194
+            throw new OCSException('The requested group could not be found', \OCP\API::RESPOND_NOT_FOUND);
195
+        }
196 196
 
197
-		// Check subadmin has access to this group
198
-		if($this->groupManager->isAdmin($user->getUID())
199
-		   || $isSubadminOfGroup) {
200
-			$users = $this->groupManager->get($groupId)->getUsers();
201
-			// Extract required number
202
-			$users = array_slice($users, $offset, $limit);
203
-			$users = array_keys($users);
204
-			$usersDetails = [];
205
-			foreach ($users as $userId) {
206
-				$userData = $this->getUserData($userId);
207
-				// Do not insert empty entry
208
-				if(!empty($userData)) {
209
-					$usersDetails[$userId] = $userData;
210
-				} else {
211
-					// Logged user does not have permissions to see this user
212
-					// only showing its id
213
-					$usersDetails[$userId] = ['id' => $userId];
214
-				}
215
-			}
216
-			return new DataResponse(['users' => $usersDetails]);
217
-		}
197
+        // Check subadmin has access to this group
198
+        if($this->groupManager->isAdmin($user->getUID())
199
+           || $isSubadminOfGroup) {
200
+            $users = $this->groupManager->get($groupId)->getUsers();
201
+            // Extract required number
202
+            $users = array_slice($users, $offset, $limit);
203
+            $users = array_keys($users);
204
+            $usersDetails = [];
205
+            foreach ($users as $userId) {
206
+                $userData = $this->getUserData($userId);
207
+                // Do not insert empty entry
208
+                if(!empty($userData)) {
209
+                    $usersDetails[$userId] = $userData;
210
+                } else {
211
+                    // Logged user does not have permissions to see this user
212
+                    // only showing its id
213
+                    $usersDetails[$userId] = ['id' => $userId];
214
+                }
215
+            }
216
+            return new DataResponse(['users' => $usersDetails]);
217
+        }
218 218
 
219
-		throw new OCSException('User does not have access to specified group', \OCP\API::RESPOND_UNAUTHORISED);
220
-	}
219
+        throw new OCSException('User does not have access to specified group', \OCP\API::RESPOND_UNAUTHORISED);
220
+    }
221 221
 
222
-	/**
223
-	 * creates a new group
224
-	 *
225
-	 * @PasswordConfirmationRequired
226
-	 *
227
-	 * @param string $groupid
228
-	 * @return DataResponse
229
-	 * @throws OCSException
230
-	 */
231
-	public function addGroup(string $groupid): DataResponse {
232
-		// Validate name
233
-		if(empty($groupid)) {
234
-			$this->logger->error('Group name not supplied', ['app' => 'provisioning_api']);
235
-			throw new OCSException('Invalid group name', 101);
236
-		}
237
-		// Check if it exists
238
-		if($this->groupManager->groupExists($groupid)){
239
-			throw new OCSException('', 102);
240
-		}
241
-		$this->groupManager->createGroup($groupid);
242
-		return new DataResponse();
243
-	}
222
+    /**
223
+     * creates a new group
224
+     *
225
+     * @PasswordConfirmationRequired
226
+     *
227
+     * @param string $groupid
228
+     * @return DataResponse
229
+     * @throws OCSException
230
+     */
231
+    public function addGroup(string $groupid): DataResponse {
232
+        // Validate name
233
+        if(empty($groupid)) {
234
+            $this->logger->error('Group name not supplied', ['app' => 'provisioning_api']);
235
+            throw new OCSException('Invalid group name', 101);
236
+        }
237
+        // Check if it exists
238
+        if($this->groupManager->groupExists($groupid)){
239
+            throw new OCSException('', 102);
240
+        }
241
+        $this->groupManager->createGroup($groupid);
242
+        return new DataResponse();
243
+    }
244 244
 
245
-	/**
246
-	 * @PasswordConfirmationRequired
247
-	 *
248
-	 * @param string $groupId
249
-	 * @return DataResponse
250
-	 * @throws OCSException
251
-	 */
252
-	public function deleteGroup(string $groupId): DataResponse {
253
-		// Check it exists
254
-		if(!$this->groupManager->groupExists($groupId)){
255
-			throw new OCSException('', 101);
256
-		} else if($groupId === 'admin' || !$this->groupManager->get($groupId)->delete()){
257
-			// Cannot delete admin group
258
-			throw new OCSException('', 102);
259
-		}
245
+    /**
246
+     * @PasswordConfirmationRequired
247
+     *
248
+     * @param string $groupId
249
+     * @return DataResponse
250
+     * @throws OCSException
251
+     */
252
+    public function deleteGroup(string $groupId): DataResponse {
253
+        // Check it exists
254
+        if(!$this->groupManager->groupExists($groupId)){
255
+            throw new OCSException('', 101);
256
+        } else if($groupId === 'admin' || !$this->groupManager->get($groupId)->delete()){
257
+            // Cannot delete admin group
258
+            throw new OCSException('', 102);
259
+        }
260 260
 
261
-		return new DataResponse();
262
-	}
261
+        return new DataResponse();
262
+    }
263 263
 
264
-	/**
265
-	 * @param string $groupId
266
-	 * @return DataResponse
267
-	 * @throws OCSException
268
-	 */
269
-	public function getSubAdminsOfGroup(string $groupId): DataResponse {
270
-		// Check group exists
271
-		$targetGroup = $this->groupManager->get($groupId);
272
-		if($targetGroup === null) {
273
-			throw new OCSException('Group does not exist', 101);
274
-		}
264
+    /**
265
+     * @param string $groupId
266
+     * @return DataResponse
267
+     * @throws OCSException
268
+     */
269
+    public function getSubAdminsOfGroup(string $groupId): DataResponse {
270
+        // Check group exists
271
+        $targetGroup = $this->groupManager->get($groupId);
272
+        if($targetGroup === null) {
273
+            throw new OCSException('Group does not exist', 101);
274
+        }
275 275
 
276
-		/** @var IUser[] $subadmins */
277
-		$subadmins = $this->groupManager->getSubAdmin()->getGroupsSubAdmins($targetGroup);
278
-		// New class returns IUser[] so convert back
279
-		$uids = [];
280
-		foreach ($subadmins as $user) {
281
-			$uids[] = $user->getUID();
282
-		}
276
+        /** @var IUser[] $subadmins */
277
+        $subadmins = $this->groupManager->getSubAdmin()->getGroupsSubAdmins($targetGroup);
278
+        // New class returns IUser[] so convert back
279
+        $uids = [];
280
+        foreach ($subadmins as $user) {
281
+            $uids[] = $user->getUID();
282
+        }
283 283
 
284
-		return new DataResponse($uids);
285
-	}
284
+        return new DataResponse($uids);
285
+    }
286 286
 
287 287
 }
Please login to merge, or discard this patch.
settings/Controller/UsersController.php 1 patch
Indentation   +368 added lines, -368 removed lines patch added patch discarded remove patch
@@ -65,402 +65,402 @@
 block discarded – undo
65 65
  * @package OC\Settings\Controller
66 66
  */
67 67
 class UsersController extends Controller {
68
-	/** @var IUserManager */
69
-	private $userManager;
70
-	/** @var IGroupManager */
71
-	private $groupManager;
72
-	/** @var IUserSession */
73
-	private $userSession;
74
-	/** @var IConfig */
75
-	private $config;
76
-	/** @var bool */
77
-	private $isAdmin;
78
-	/** @var IL10N */
79
-	private $l10n;
80
-	/** @var IMailer */
81
-	private $mailer;
82
-	/** @var IFactory */
83
-	private $l10nFactory;
84
-	/** @var IAppManager */
85
-	private $appManager;
86
-	/** @var AccountManager */
87
-	private $accountManager;
88
-	/** @var Manager */
89
-	private $keyManager;
90
-	/** @var IJobList */
91
-	private $jobList;
92
-	/** @var IManager */
93
-	private $encryptionManager;
68
+    /** @var IUserManager */
69
+    private $userManager;
70
+    /** @var IGroupManager */
71
+    private $groupManager;
72
+    /** @var IUserSession */
73
+    private $userSession;
74
+    /** @var IConfig */
75
+    private $config;
76
+    /** @var bool */
77
+    private $isAdmin;
78
+    /** @var IL10N */
79
+    private $l10n;
80
+    /** @var IMailer */
81
+    private $mailer;
82
+    /** @var IFactory */
83
+    private $l10nFactory;
84
+    /** @var IAppManager */
85
+    private $appManager;
86
+    /** @var AccountManager */
87
+    private $accountManager;
88
+    /** @var Manager */
89
+    private $keyManager;
90
+    /** @var IJobList */
91
+    private $jobList;
92
+    /** @var IManager */
93
+    private $encryptionManager;
94 94
 
95 95
 
96
-	public function __construct(string $appName,
97
-								IRequest $request,
98
-								IUserManager $userManager,
99
-								IGroupManager $groupManager,
100
-								IUserSession $userSession,
101
-								IConfig $config,
102
-								bool $isAdmin,
103
-								IL10N $l10n,
104
-								IMailer $mailer,
105
-								IFactory $l10nFactory,
106
-								IAppManager $appManager,
107
-								AccountManager $accountManager,
108
-								Manager $keyManager,
109
-								IJobList $jobList,
110
-								IManager $encryptionManager) {
111
-		parent::__construct($appName, $request);
112
-		$this->userManager = $userManager;
113
-		$this->groupManager = $groupManager;
114
-		$this->userSession = $userSession;
115
-		$this->config = $config;
116
-		$this->isAdmin = $isAdmin;
117
-		$this->l10n = $l10n;
118
-		$this->mailer = $mailer;
119
-		$this->l10nFactory = $l10nFactory;
120
-		$this->appManager = $appManager;
121
-		$this->accountManager = $accountManager;
122
-		$this->keyManager = $keyManager;
123
-		$this->jobList = $jobList;
124
-		$this->encryptionManager = $encryptionManager;
125
-	}
96
+    public function __construct(string $appName,
97
+                                IRequest $request,
98
+                                IUserManager $userManager,
99
+                                IGroupManager $groupManager,
100
+                                IUserSession $userSession,
101
+                                IConfig $config,
102
+                                bool $isAdmin,
103
+                                IL10N $l10n,
104
+                                IMailer $mailer,
105
+                                IFactory $l10nFactory,
106
+                                IAppManager $appManager,
107
+                                AccountManager $accountManager,
108
+                                Manager $keyManager,
109
+                                IJobList $jobList,
110
+                                IManager $encryptionManager) {
111
+        parent::__construct($appName, $request);
112
+        $this->userManager = $userManager;
113
+        $this->groupManager = $groupManager;
114
+        $this->userSession = $userSession;
115
+        $this->config = $config;
116
+        $this->isAdmin = $isAdmin;
117
+        $this->l10n = $l10n;
118
+        $this->mailer = $mailer;
119
+        $this->l10nFactory = $l10nFactory;
120
+        $this->appManager = $appManager;
121
+        $this->accountManager = $accountManager;
122
+        $this->keyManager = $keyManager;
123
+        $this->jobList = $jobList;
124
+        $this->encryptionManager = $encryptionManager;
125
+    }
126 126
 
127 127
 
128
-	/**
129
-	 * @NoCSRFRequired
130
-	 * @NoAdminRequired
131
-	 * 
132
-	 * Display users list template
133
-	 * 
134
-	 * @return TemplateResponse
135
-	 */
136
-	public function usersListByGroup() {
137
-		return $this->usersList();
138
-	}
128
+    /**
129
+     * @NoCSRFRequired
130
+     * @NoAdminRequired
131
+     * 
132
+     * Display users list template
133
+     * 
134
+     * @return TemplateResponse
135
+     */
136
+    public function usersListByGroup() {
137
+        return $this->usersList();
138
+    }
139 139
 
140
-	/**
141
-	 * @NoCSRFRequired
142
-	 * @NoAdminRequired
143
-	 * 
144
-	 * Display users list template
145
-	 * 
146
-	 * @return TemplateResponse
147
-	 */
148
-	public function usersList() {
149
-		$user = $this->userSession->getUser();
150
-		$uid = $user->getUID();
140
+    /**
141
+     * @NoCSRFRequired
142
+     * @NoAdminRequired
143
+     * 
144
+     * Display users list template
145
+     * 
146
+     * @return TemplateResponse
147
+     */
148
+    public function usersList() {
149
+        $user = $this->userSession->getUser();
150
+        $uid = $user->getUID();
151 151
 
152
-		\OC::$server->getNavigationManager()->setActiveEntry('core_users');
152
+        \OC::$server->getNavigationManager()->setActiveEntry('core_users');
153 153
 				
154
-		/* SORT OPTION: SORT_USERCOUNT or SORT_GROUPNAME */
155
-		$sortGroupsBy = \OC\Group\MetaData::SORT_USERCOUNT;
156
-		if ($this->config->getSystemValue('sort_groups_by_name', false)) {
157
-			$sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
158
-		} else {
159
-			$isLDAPUsed = false;
160
-			if ($this->appManager->isEnabledForUser('user_ldap')) {
161
-				$isLDAPUsed =
162
-					$this->groupManager->isBackendUsed('\OCA\User_LDAP\Group_LDAP')
163
-					|| $this->groupManager->isBackendUsed('\OCA\User_LDAP\Group_Proxy');
164
-				if ($isLDAPUsed) {
165
-					// LDAP user count can be slow, so we sort by group name here
166
-					$sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
167
-				}
168
-			}
169
-		}
154
+        /* SORT OPTION: SORT_USERCOUNT or SORT_GROUPNAME */
155
+        $sortGroupsBy = \OC\Group\MetaData::SORT_USERCOUNT;
156
+        if ($this->config->getSystemValue('sort_groups_by_name', false)) {
157
+            $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
158
+        } else {
159
+            $isLDAPUsed = false;
160
+            if ($this->appManager->isEnabledForUser('user_ldap')) {
161
+                $isLDAPUsed =
162
+                    $this->groupManager->isBackendUsed('\OCA\User_LDAP\Group_LDAP')
163
+                    || $this->groupManager->isBackendUsed('\OCA\User_LDAP\Group_Proxy');
164
+                if ($isLDAPUsed) {
165
+                    // LDAP user count can be slow, so we sort by group name here
166
+                    $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
167
+                }
168
+            }
169
+        }
170 170
 		
171
-		/* ENCRYPTION CONFIG */
172
-		$isEncryptionEnabled = $this->encryptionManager->isEnabled();
173
-		$useMasterKey = $this->config->getAppValue('encryption', 'useMasterKey', true);
174
-		// If masterKey enabled, then you can change password. This is to avoid data loss!
175
-		$canChangePassword = ($isEncryptionEnabled && $useMasterKey) || $useMasterKey;
171
+        /* ENCRYPTION CONFIG */
172
+        $isEncryptionEnabled = $this->encryptionManager->isEnabled();
173
+        $useMasterKey = $this->config->getAppValue('encryption', 'useMasterKey', true);
174
+        // If masterKey enabled, then you can change password. This is to avoid data loss!
175
+        $canChangePassword = ($isEncryptionEnabled && $useMasterKey) || $useMasterKey;
176 176
 		
177 177
 		
178
-		/* GROUPS */		
179
-		$groupsInfo = new \OC\Group\MetaData(
180
-			$uid,
181
-			$this->isAdmin,
182
-			$this->groupManager,
183
-			$this->userSession
184
-		);
178
+        /* GROUPS */		
179
+        $groupsInfo = new \OC\Group\MetaData(
180
+            $uid,
181
+            $this->isAdmin,
182
+            $this->groupManager,
183
+            $this->userSession
184
+        );
185 185
 		
186
-		$groupsInfo->setSorting($sortGroupsBy);
187
-		list($adminGroup, $groups) = $groupsInfo->get();
186
+        $groupsInfo->setSorting($sortGroupsBy);
187
+        list($adminGroup, $groups) = $groupsInfo->get();
188 188
 		
189
-		if ($this->isAdmin) {
190
-			$disabledUsers = $isLDAPUsed ? 0 : $this->userManager->countDisabledUsers();
191
-			$userCount = array_reduce($this->userManager->countUsers(), function($v, $w) {
192
-				return $v + (int)$w;
193
-			}, 0);
194
-		} else {
195
-			// User is subadmin !
196
-			// Map group list to names to retrieve the countDisabledUsersOfGroups
197
-			$userGroups = $this->groupManager->getUserGroups($user);
198
-			$groupsNames = [];
199
-			$userCount = 0;
189
+        if ($this->isAdmin) {
190
+            $disabledUsers = $isLDAPUsed ? 0 : $this->userManager->countDisabledUsers();
191
+            $userCount = array_reduce($this->userManager->countUsers(), function($v, $w) {
192
+                return $v + (int)$w;
193
+            }, 0);
194
+        } else {
195
+            // User is subadmin !
196
+            // Map group list to names to retrieve the countDisabledUsersOfGroups
197
+            $userGroups = $this->groupManager->getUserGroups($user);
198
+            $groupsNames = [];
199
+            $userCount = 0;
200 200
 
201
-			foreach($groups as $key => $group) {
202
-				// $userCount += (int)$group['usercount'];
203
-				array_push($groupsNames, $group['name']);
204
-				// we prevent subadmins from looking up themselves
205
-				// so we lower the count of the groups he belongs to
206
-				if (array_key_exists($group['id'], $userGroups)) {
207
-					$groups[$key]['usercount']--;
208
-					$userCount = -1; // we also lower from one the total count
209
-				}
210
-			};
211
-			$userCount += $this->userManager->countUsersOfGroups($groupsInfo->getGroups());
212
-			$disabledUsers = $isLDAPUsed ? 0 : $this->userManager->countDisabledUsersOfGroups($groupsNames);
213
-		}
214
-		$disabledUsersGroup = [
215
-			'id' => 'disabled',
216
-			'name' => 'Disabled users',
217
-			'usercount' => $disabledUsers
218
-		];
201
+            foreach($groups as $key => $group) {
202
+                // $userCount += (int)$group['usercount'];
203
+                array_push($groupsNames, $group['name']);
204
+                // we prevent subadmins from looking up themselves
205
+                // so we lower the count of the groups he belongs to
206
+                if (array_key_exists($group['id'], $userGroups)) {
207
+                    $groups[$key]['usercount']--;
208
+                    $userCount = -1; // we also lower from one the total count
209
+                }
210
+            };
211
+            $userCount += $this->userManager->countUsersOfGroups($groupsInfo->getGroups());
212
+            $disabledUsers = $isLDAPUsed ? 0 : $this->userManager->countDisabledUsersOfGroups($groupsNames);
213
+        }
214
+        $disabledUsersGroup = [
215
+            'id' => 'disabled',
216
+            'name' => 'Disabled users',
217
+            'usercount' => $disabledUsers
218
+        ];
219 219
 		
220
-		/* QUOTAS PRESETS */
221
-		$quotaPreset = $this->config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
222
-		$quotaPreset = explode(',', $quotaPreset);
223
-		foreach ($quotaPreset as &$preset) {
224
-			$preset = trim($preset);
225
-		}
226
-		$quotaPreset = array_diff($quotaPreset, array('default', 'none'));
227
-		$defaultQuota = $this->config->getAppValue('files', 'default_quota', 'none');
220
+        /* QUOTAS PRESETS */
221
+        $quotaPreset = $this->config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
222
+        $quotaPreset = explode(',', $quotaPreset);
223
+        foreach ($quotaPreset as &$preset) {
224
+            $preset = trim($preset);
225
+        }
226
+        $quotaPreset = array_diff($quotaPreset, array('default', 'none'));
227
+        $defaultQuota = $this->config->getAppValue('files', 'default_quota', 'none');
228 228
 		
229
-		\OC::$server->getEventDispatcher()->dispatch('OC\Settings\Users::loadAdditionalScripts');
229
+        \OC::$server->getEventDispatcher()->dispatch('OC\Settings\Users::loadAdditionalScripts');
230 230
 		
231
-		/* LANGUAGES */
232
-		$languages = $this->l10nFactory->getLanguages();
231
+        /* LANGUAGES */
232
+        $languages = $this->l10nFactory->getLanguages();
233 233
 		
234
-		/* FINAL DATA */
235
-		$serverData = array();
236
-		// groups
237
-		$serverData['groups'] = array_merge_recursive($adminGroup, [$disabledUsersGroup], $groups);
238
-		// Various data
239
-		$serverData['isAdmin'] = $this->isAdmin;
240
-		$serverData['sortGroups'] = $sortGroupsBy;
241
-		$serverData['quotaPreset'] = $quotaPreset;
242
-		$serverData['userCount'] = $userCount - $disabledUsers;
243
-		$serverData['languages'] = $languages;
244
-		$serverData['defaultLanguage'] = $this->config->getSystemValue('default_language', 'en');
245
-		// Settings
246
-		$serverData['defaultQuota'] = $defaultQuota;
247
-		$serverData['canChangePassword'] = $canChangePassword;
234
+        /* FINAL DATA */
235
+        $serverData = array();
236
+        // groups
237
+        $serverData['groups'] = array_merge_recursive($adminGroup, [$disabledUsersGroup], $groups);
238
+        // Various data
239
+        $serverData['isAdmin'] = $this->isAdmin;
240
+        $serverData['sortGroups'] = $sortGroupsBy;
241
+        $serverData['quotaPreset'] = $quotaPreset;
242
+        $serverData['userCount'] = $userCount - $disabledUsers;
243
+        $serverData['languages'] = $languages;
244
+        $serverData['defaultLanguage'] = $this->config->getSystemValue('default_language', 'en');
245
+        // Settings
246
+        $serverData['defaultQuota'] = $defaultQuota;
247
+        $serverData['canChangePassword'] = $canChangePassword;
248 248
 
249
-		return new TemplateResponse('settings', 'settings', ['serverData' => $serverData]);
250
-	}
249
+        return new TemplateResponse('settings', 'settings', ['serverData' => $serverData]);
250
+    }
251 251
 
252
-	/**
253
-	 * @NoAdminRequired
254
-	 * @NoSubadminRequired
255
-	 * @PasswordConfirmationRequired
256
-	 *
257
-	 * @param string $avatarScope
258
-	 * @param string $displayname
259
-	 * @param string $displaynameScope
260
-	 * @param string $phone
261
-	 * @param string $phoneScope
262
-	 * @param string $email
263
-	 * @param string $emailScope
264
-	 * @param string $website
265
-	 * @param string $websiteScope
266
-	 * @param string $address
267
-	 * @param string $addressScope
268
-	 * @param string $twitter
269
-	 * @param string $twitterScope
270
-	 * @return DataResponse
271
-	 */
272
-	public function setUserSettings($avatarScope,
273
-									$displayname,
274
-									$displaynameScope,
275
-									$phone,
276
-									$phoneScope,
277
-									$email,
278
-									$emailScope,
279
-									$website,
280
-									$websiteScope,
281
-									$address,
282
-									$addressScope,
283
-									$twitter,
284
-									$twitterScope
285
-	) {
286
-		if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
287
-			return new DataResponse(
288
-				[
289
-					'status' => 'error',
290
-					'data' => [
291
-						'message' => $this->l10n->t('Invalid mail address')
292
-					]
293
-				],
294
-				Http::STATUS_UNPROCESSABLE_ENTITY
295
-			);
296
-		}
297
-		$user = $this->userSession->getUser();
298
-		$data = $this->accountManager->getUser($user);
299
-		$data[AccountManager::PROPERTY_AVATAR] = ['scope' => $avatarScope];
300
-		if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
301
-			$data[AccountManager::PROPERTY_DISPLAYNAME] = ['value' => $displayname, 'scope' => $displaynameScope];
302
-			$data[AccountManager::PROPERTY_EMAIL] = ['value' => $email, 'scope' => $emailScope];
303
-		}
304
-		if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
305
-			$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
306
-			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
307
-			if ($shareProvider->isLookupServerUploadEnabled()) {
308
-				$data[AccountManager::PROPERTY_WEBSITE] = ['value' => $website, 'scope' => $websiteScope];
309
-				$data[AccountManager::PROPERTY_ADDRESS] = ['value' => $address, 'scope' => $addressScope];
310
-				$data[AccountManager::PROPERTY_PHONE] = ['value' => $phone, 'scope' => $phoneScope];
311
-				$data[AccountManager::PROPERTY_TWITTER] = ['value' => $twitter, 'scope' => $twitterScope];
312
-			}
313
-		}
314
-		try {
315
-			$this->saveUserSettings($user, $data);
316
-			return new DataResponse(
317
-				[
318
-					'status' => 'success',
319
-					'data' => [
320
-						'userId' => $user->getUID(),
321
-						'avatarScope' => $data[AccountManager::PROPERTY_AVATAR]['scope'],
322
-						'displayname' => $data[AccountManager::PROPERTY_DISPLAYNAME]['value'],
323
-						'displaynameScope' => $data[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
324
-						'email' => $data[AccountManager::PROPERTY_EMAIL]['value'],
325
-						'emailScope' => $data[AccountManager::PROPERTY_EMAIL]['scope'],
326
-						'website' => $data[AccountManager::PROPERTY_WEBSITE]['value'],
327
-						'websiteScope' => $data[AccountManager::PROPERTY_WEBSITE]['scope'],
328
-						'address' => $data[AccountManager::PROPERTY_ADDRESS]['value'],
329
-						'addressScope' => $data[AccountManager::PROPERTY_ADDRESS]['scope'],
330
-						'message' => $this->l10n->t('Settings saved')
331
-					]
332
-				],
333
-				Http::STATUS_OK
334
-			);
335
-		} catch (ForbiddenException $e) {
336
-			return new DataResponse([
337
-				'status' => 'error',
338
-				'data' => [
339
-					'message' => $e->getMessage()
340
-				],
341
-			]);
342
-		}
343
-	}
344
-	/**
345
-	 * update account manager with new user data
346
-	 *
347
-	 * @param IUser $user
348
-	 * @param array $data
349
-	 * @throws ForbiddenException
350
-	 */
351
-	protected function saveUserSettings(IUser $user, array $data) {
352
-		// keep the user back-end up-to-date with the latest display name and email
353
-		// address
354
-		$oldDisplayName = $user->getDisplayName();
355
-		$oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
356
-		if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
357
-			&& $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
358
-		) {
359
-			$result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
360
-			if ($result === false) {
361
-				throw new ForbiddenException($this->l10n->t('Unable to change full name'));
362
-			}
363
-		}
364
-		$oldEmailAddress = $user->getEMailAddress();
365
-		$oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
366
-		if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
367
-			&& $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
368
-		) {
369
-			// this is the only permission a backend provides and is also used
370
-			// for the permission of setting a email address
371
-			if (!$user->canChangeDisplayName()) {
372
-				throw new ForbiddenException($this->l10n->t('Unable to change email address'));
373
-			}
374
-			$user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
375
-		}
376
-		$this->accountManager->updateUser($user, $data);
377
-	}
252
+    /**
253
+     * @NoAdminRequired
254
+     * @NoSubadminRequired
255
+     * @PasswordConfirmationRequired
256
+     *
257
+     * @param string $avatarScope
258
+     * @param string $displayname
259
+     * @param string $displaynameScope
260
+     * @param string $phone
261
+     * @param string $phoneScope
262
+     * @param string $email
263
+     * @param string $emailScope
264
+     * @param string $website
265
+     * @param string $websiteScope
266
+     * @param string $address
267
+     * @param string $addressScope
268
+     * @param string $twitter
269
+     * @param string $twitterScope
270
+     * @return DataResponse
271
+     */
272
+    public function setUserSettings($avatarScope,
273
+                                    $displayname,
274
+                                    $displaynameScope,
275
+                                    $phone,
276
+                                    $phoneScope,
277
+                                    $email,
278
+                                    $emailScope,
279
+                                    $website,
280
+                                    $websiteScope,
281
+                                    $address,
282
+                                    $addressScope,
283
+                                    $twitter,
284
+                                    $twitterScope
285
+    ) {
286
+        if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
287
+            return new DataResponse(
288
+                [
289
+                    'status' => 'error',
290
+                    'data' => [
291
+                        'message' => $this->l10n->t('Invalid mail address')
292
+                    ]
293
+                ],
294
+                Http::STATUS_UNPROCESSABLE_ENTITY
295
+            );
296
+        }
297
+        $user = $this->userSession->getUser();
298
+        $data = $this->accountManager->getUser($user);
299
+        $data[AccountManager::PROPERTY_AVATAR] = ['scope' => $avatarScope];
300
+        if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
301
+            $data[AccountManager::PROPERTY_DISPLAYNAME] = ['value' => $displayname, 'scope' => $displaynameScope];
302
+            $data[AccountManager::PROPERTY_EMAIL] = ['value' => $email, 'scope' => $emailScope];
303
+        }
304
+        if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
305
+            $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
306
+            $shareProvider = $federatedFileSharing->getFederatedShareProvider();
307
+            if ($shareProvider->isLookupServerUploadEnabled()) {
308
+                $data[AccountManager::PROPERTY_WEBSITE] = ['value' => $website, 'scope' => $websiteScope];
309
+                $data[AccountManager::PROPERTY_ADDRESS] = ['value' => $address, 'scope' => $addressScope];
310
+                $data[AccountManager::PROPERTY_PHONE] = ['value' => $phone, 'scope' => $phoneScope];
311
+                $data[AccountManager::PROPERTY_TWITTER] = ['value' => $twitter, 'scope' => $twitterScope];
312
+            }
313
+        }
314
+        try {
315
+            $this->saveUserSettings($user, $data);
316
+            return new DataResponse(
317
+                [
318
+                    'status' => 'success',
319
+                    'data' => [
320
+                        'userId' => $user->getUID(),
321
+                        'avatarScope' => $data[AccountManager::PROPERTY_AVATAR]['scope'],
322
+                        'displayname' => $data[AccountManager::PROPERTY_DISPLAYNAME]['value'],
323
+                        'displaynameScope' => $data[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
324
+                        'email' => $data[AccountManager::PROPERTY_EMAIL]['value'],
325
+                        'emailScope' => $data[AccountManager::PROPERTY_EMAIL]['scope'],
326
+                        'website' => $data[AccountManager::PROPERTY_WEBSITE]['value'],
327
+                        'websiteScope' => $data[AccountManager::PROPERTY_WEBSITE]['scope'],
328
+                        'address' => $data[AccountManager::PROPERTY_ADDRESS]['value'],
329
+                        'addressScope' => $data[AccountManager::PROPERTY_ADDRESS]['scope'],
330
+                        'message' => $this->l10n->t('Settings saved')
331
+                    ]
332
+                ],
333
+                Http::STATUS_OK
334
+            );
335
+        } catch (ForbiddenException $e) {
336
+            return new DataResponse([
337
+                'status' => 'error',
338
+                'data' => [
339
+                    'message' => $e->getMessage()
340
+                ],
341
+            ]);
342
+        }
343
+    }
344
+    /**
345
+     * update account manager with new user data
346
+     *
347
+     * @param IUser $user
348
+     * @param array $data
349
+     * @throws ForbiddenException
350
+     */
351
+    protected function saveUserSettings(IUser $user, array $data) {
352
+        // keep the user back-end up-to-date with the latest display name and email
353
+        // address
354
+        $oldDisplayName = $user->getDisplayName();
355
+        $oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
356
+        if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
357
+            && $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
358
+        ) {
359
+            $result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
360
+            if ($result === false) {
361
+                throw new ForbiddenException($this->l10n->t('Unable to change full name'));
362
+            }
363
+        }
364
+        $oldEmailAddress = $user->getEMailAddress();
365
+        $oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
366
+        if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
367
+            && $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
368
+        ) {
369
+            // this is the only permission a backend provides and is also used
370
+            // for the permission of setting a email address
371
+            if (!$user->canChangeDisplayName()) {
372
+                throw new ForbiddenException($this->l10n->t('Unable to change email address'));
373
+            }
374
+            $user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
375
+        }
376
+        $this->accountManager->updateUser($user, $data);
377
+    }
378 378
 
379
-	/**
380
-	 * Set the mail address of a user
381
-	 *
382
-	 * @NoAdminRequired
383
-	 * @NoSubadminRequired
384
-	 * @PasswordConfirmationRequired
385
-	 *
386
-	 * @param string $account
387
-	 * @param bool $onlyVerificationCode only return verification code without updating the data
388
-	 * @return DataResponse
389
-	 */
390
-	public function getVerificationCode(string $account, bool $onlyVerificationCode): DataResponse {
379
+    /**
380
+     * Set the mail address of a user
381
+     *
382
+     * @NoAdminRequired
383
+     * @NoSubadminRequired
384
+     * @PasswordConfirmationRequired
385
+     *
386
+     * @param string $account
387
+     * @param bool $onlyVerificationCode only return verification code without updating the data
388
+     * @return DataResponse
389
+     */
390
+    public function getVerificationCode(string $account, bool $onlyVerificationCode): DataResponse {
391 391
 
392
-		$user = $this->userSession->getUser();
392
+        $user = $this->userSession->getUser();
393 393
 
394
-		if ($user === null) {
395
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
396
-		}
394
+        if ($user === null) {
395
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
396
+        }
397 397
 
398
-		$accountData = $this->accountManager->getUser($user);
399
-		$cloudId = $user->getCloudId();
400
-		$message = 'Use my Federated Cloud ID to share with me: ' . $cloudId;
401
-		$signature = $this->signMessage($user, $message);
398
+        $accountData = $this->accountManager->getUser($user);
399
+        $cloudId = $user->getCloudId();
400
+        $message = 'Use my Federated Cloud ID to share with me: ' . $cloudId;
401
+        $signature = $this->signMessage($user, $message);
402 402
 
403
-		$code = $message . ' ' . $signature;
404
-		$codeMd5 = $message . ' ' . md5($signature);
403
+        $code = $message . ' ' . $signature;
404
+        $codeMd5 = $message . ' ' . md5($signature);
405 405
 
406
-		switch ($account) {
407
-			case 'verify-twitter':
408
-				$accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
409
-				$msg = $this->l10n->t('In order to verify your Twitter account, post the following tweet on Twitter (please make sure to post it without any line breaks):');
410
-				$code = $codeMd5;
411
-				$type = AccountManager::PROPERTY_TWITTER;
412
-				$data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
413
-				$accountData[AccountManager::PROPERTY_TWITTER]['signature'] = $signature;
414
-				break;
415
-			case 'verify-website':
416
-				$accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
417
-				$msg = $this->l10n->t('In order to verify your Website, store the following content in your web-root at \'.well-known/CloudIdVerificationCode.txt\' (please make sure that the complete text is in one line):');
418
-				$type = AccountManager::PROPERTY_WEBSITE;
419
-				$data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
420
-				$accountData[AccountManager::PROPERTY_WEBSITE]['signature'] = $signature;
421
-				break;
422
-			default:
423
-				return new DataResponse([], Http::STATUS_BAD_REQUEST);
424
-		}
406
+        switch ($account) {
407
+            case 'verify-twitter':
408
+                $accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
409
+                $msg = $this->l10n->t('In order to verify your Twitter account, post the following tweet on Twitter (please make sure to post it without any line breaks):');
410
+                $code = $codeMd5;
411
+                $type = AccountManager::PROPERTY_TWITTER;
412
+                $data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
413
+                $accountData[AccountManager::PROPERTY_TWITTER]['signature'] = $signature;
414
+                break;
415
+            case 'verify-website':
416
+                $accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
417
+                $msg = $this->l10n->t('In order to verify your Website, store the following content in your web-root at \'.well-known/CloudIdVerificationCode.txt\' (please make sure that the complete text is in one line):');
418
+                $type = AccountManager::PROPERTY_WEBSITE;
419
+                $data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
420
+                $accountData[AccountManager::PROPERTY_WEBSITE]['signature'] = $signature;
421
+                break;
422
+            default:
423
+                return new DataResponse([], Http::STATUS_BAD_REQUEST);
424
+        }
425 425
 
426
-		if ($onlyVerificationCode === false) {
427
-			$this->accountManager->updateUser($user, $accountData);
426
+        if ($onlyVerificationCode === false) {
427
+            $this->accountManager->updateUser($user, $accountData);
428 428
 
429
-			$this->jobList->add(VerifyUserData::class,
430
-				[
431
-					'verificationCode' => $code,
432
-					'data' => $data,
433
-					'type' => $type,
434
-					'uid' => $user->getUID(),
435
-					'try' => 0,
436
-					'lastRun' => $this->getCurrentTime()
437
-				]
438
-			);
439
-		}
429
+            $this->jobList->add(VerifyUserData::class,
430
+                [
431
+                    'verificationCode' => $code,
432
+                    'data' => $data,
433
+                    'type' => $type,
434
+                    'uid' => $user->getUID(),
435
+                    'try' => 0,
436
+                    'lastRun' => $this->getCurrentTime()
437
+                ]
438
+            );
439
+        }
440 440
 
441
-		return new DataResponse(['msg' => $msg, 'code' => $code]);
442
-	}
441
+        return new DataResponse(['msg' => $msg, 'code' => $code]);
442
+    }
443 443
 
444
-	/**
445
-	 * get current timestamp
446
-	 *
447
-	 * @return int
448
-	 */
449
-	protected function getCurrentTime(): int {
450
-		return time();
451
-	}
444
+    /**
445
+     * get current timestamp
446
+     *
447
+     * @return int
448
+     */
449
+    protected function getCurrentTime(): int {
450
+        return time();
451
+    }
452 452
 
453
-	/**
454
-	 * sign message with users private key
455
-	 *
456
-	 * @param IUser $user
457
-	 * @param string $message
458
-	 *
459
-	 * @return string base64 encoded signature
460
-	 */
461
-	protected function signMessage(IUser $user, string $message): string {
462
-		$privateKey = $this->keyManager->getKey($user)->getPrivate();
463
-		openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
464
-		return base64_encode($signature);
465
-	}
453
+    /**
454
+     * sign message with users private key
455
+     *
456
+     * @param IUser $user
457
+     * @param string $message
458
+     *
459
+     * @return string base64 encoded signature
460
+     */
461
+    protected function signMessage(IUser $user, string $message): string {
462
+        $privateKey = $this->keyManager->getKey($user)->getPrivate();
463
+        openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
464
+        return base64_encode($signature);
465
+    }
466 466
 }
Please login to merge, or discard this patch.
lib/private/Group/MetaData.php 1 patch
Indentation   +170 added lines, -170 removed lines patch added patch discarded remove patch
@@ -32,174 +32,174 @@
 block discarded – undo
32 32
 use OCP\IGroupManager;
33 33
 
34 34
 class MetaData {
35
-	const SORT_NONE = 0;
36
-	const SORT_USERCOUNT = 1; // May have performance issues on LDAP backends
37
-	const SORT_GROUPNAME = 2;
38
-
39
-	/** @var string */
40
-	protected $user;
41
-	/** @var bool */
42
-	protected $isAdmin;
43
-	/** @var array */
44
-	protected $metaData = array();
45
-	/** @var IGroupManager */
46
-	protected $groupManager;
47
-	/** @var bool */
48
-	protected $sorting = false;
49
-	/** @var IUserSession */
50
-	protected $userSession;
51
-
52
-	/**
53
-	 * @param string $user the uid of the current user
54
-	 * @param bool $isAdmin whether the current users is an admin
55
-	 * @param IGroupManager $groupManager
56
-	 * @param IUserManager $userManager
57
-	 * @param IUserSession $userSession
58
-	 */
59
-	public function __construct(
60
-			$user,
61
-			$isAdmin,
62
-			IGroupManager $groupManager,
63
-			IUserSession $userSession
64
-			) {
65
-		$this->user = $user;
66
-		$this->isAdmin = (bool)$isAdmin;
67
-		$this->groupManager = $groupManager;
68
-		$this->userSession = $userSession;
69
-	}
70
-
71
-	/**
72
-	 * returns an array with meta data about all available groups
73
-	 * the array is structured as follows:
74
-	 * [0] array containing meta data about admin groups
75
-	 * [1] array containing meta data about unprivileged groups
76
-	 * @param string $groupSearch only effective when instance was created with
77
-	 * isAdmin being true
78
-	 * @param string $userSearch the pattern users are search for
79
-	 * @return array
80
-	 */
81
-	public function get($groupSearch = '', $userSearch = '') {
82
-		$key = $groupSearch . '::' . $userSearch;
83
-		if(isset($this->metaData[$key])) {
84
-			return $this->metaData[$key];
85
-		}
86
-
87
-		$adminGroups = array();
88
-		$groups = array();
89
-		$sortGroupsIndex = 0;
90
-		$sortGroupsKeys = array();
91
-		$sortAdminGroupsIndex = 0;
92
-		$sortAdminGroupsKeys = array();
93
-
94
-		foreach($this->getGroups($groupSearch) as $group) {
95
-			$groupMetaData = $this->generateGroupMetaData($group, $userSearch);
96
-			if (strtolower($group->getGID()) !== 'admin') {
97
-				$this->addEntry(
98
-					$groups,
99
-					$sortGroupsKeys,
100
-					$sortGroupsIndex,
101
-					$groupMetaData);
102
-			} else {
103
-				//admin group is hard coded to 'admin' for now. In future,
104
-				//backends may define admin groups too. Then the if statement
105
-				//has to be adjusted accordingly.
106
-				$this->addEntry(
107
-					$adminGroups,
108
-					$sortAdminGroupsKeys,
109
-					$sortAdminGroupsIndex,
110
-					$groupMetaData);
111
-			}
112
-		}
113
-
114
-		//whether sorting is necessary is will be checked in sort()
115
-		$this->sort($groups, $sortGroupsKeys);
116
-		$this->sort($adminGroups, $sortAdminGroupsKeys);
117
-
118
-		$this->metaData[$key] = array($adminGroups, $groups);
119
-		return $this->metaData[$key];
120
-	}
121
-
122
-	/**
123
-	 * sets the sort mode, see SORT_* constants for supported modes
124
-	 *
125
-	 * @param int $sortMode
126
-	 */
127
-	public function setSorting($sortMode) {
128
-		switch ($sortMode) {
129
-			case self::SORT_USERCOUNT:
130
-			case self::SORT_GROUPNAME:
131
-				$this->sorting = $sortMode;
132
-				break;
133
-
134
-			default:
135
-				$this->sorting = self::SORT_NONE;
136
-		}
137
-	}
138
-
139
-	/**
140
-	 * adds an group entry to the resulting array
141
-	 * @param array $entries the resulting array, by reference
142
-	 * @param array $sortKeys the sort key array, by reference
143
-	 * @param int $sortIndex the sort key index, by reference
144
-	 * @param array $data the group's meta data as returned by generateGroupMetaData()
145
-	 */
146
-	private function addEntry(&$entries, &$sortKeys, &$sortIndex, $data) {
147
-		$entries[] = $data;
148
-		if ($this->sorting === self::SORT_USERCOUNT) {
149
-			$sortKeys[$sortIndex] = $data['usercount'];
150
-			$sortIndex++;
151
-		} else if ($this->sorting === self::SORT_GROUPNAME) {
152
-			$sortKeys[$sortIndex] = $data['name'];
153
-			$sortIndex++;
154
-		}
155
-	}
156
-
157
-	/**
158
-	 * creates an array containing the group meta data
159
-	 * @param \OCP\IGroup $group
160
-	 * @param string $userSearch
161
-	 * @return array with the keys 'id', 'name', 'usercount' and 'disabled'
162
-	 */
163
-	private function generateGroupMetaData(\OCP\IGroup $group, $userSearch) {
164
-		return array(
165
-				'id' => $group->getGID(),
166
-				'name' => $group->getDisplayName(),
167
-				'usercount' => $this->sorting === self::SORT_USERCOUNT ? $group->count($userSearch) : 0,
168
-				'disabled' => $group->countDisabled()
169
-			);
170
-	}
171
-
172
-	/**
173
-	 * sorts the result array, if applicable
174
-	 * @param array $entries the result array, by reference
175
-	 * @param array $sortKeys the array containing the sort keys
176
-	 * @param return null
177
-	 */
178
-	private function sort(&$entries, $sortKeys) {
179
-		if ($this->sorting === self::SORT_USERCOUNT) {
180
-			array_multisort($sortKeys, SORT_DESC, $entries);
181
-		} else if ($this->sorting === self::SORT_GROUPNAME) {
182
-			array_multisort($sortKeys, SORT_ASC, $entries);
183
-		}
184
-	}
185
-
186
-	/**
187
-	 * returns the available groups
188
-	 * @param string $search a search string
189
-	 * @return \OCP\IGroup[]
190
-	 */
191
-	public function getGroups($search = '') {
192
-		if($this->isAdmin) {
193
-			return $this->groupManager->search($search);
194
-		} else {
195
-			$userObject = $this->userSession->getUser();
196
-			if($userObject !== null) {
197
-				$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($userObject);
198
-			} else {
199
-				$groups = [];
200
-			}
201
-
202
-			return $groups;
203
-		}
204
-	}
35
+    const SORT_NONE = 0;
36
+    const SORT_USERCOUNT = 1; // May have performance issues on LDAP backends
37
+    const SORT_GROUPNAME = 2;
38
+
39
+    /** @var string */
40
+    protected $user;
41
+    /** @var bool */
42
+    protected $isAdmin;
43
+    /** @var array */
44
+    protected $metaData = array();
45
+    /** @var IGroupManager */
46
+    protected $groupManager;
47
+    /** @var bool */
48
+    protected $sorting = false;
49
+    /** @var IUserSession */
50
+    protected $userSession;
51
+
52
+    /**
53
+     * @param string $user the uid of the current user
54
+     * @param bool $isAdmin whether the current users is an admin
55
+     * @param IGroupManager $groupManager
56
+     * @param IUserManager $userManager
57
+     * @param IUserSession $userSession
58
+     */
59
+    public function __construct(
60
+            $user,
61
+            $isAdmin,
62
+            IGroupManager $groupManager,
63
+            IUserSession $userSession
64
+            ) {
65
+        $this->user = $user;
66
+        $this->isAdmin = (bool)$isAdmin;
67
+        $this->groupManager = $groupManager;
68
+        $this->userSession = $userSession;
69
+    }
70
+
71
+    /**
72
+     * returns an array with meta data about all available groups
73
+     * the array is structured as follows:
74
+     * [0] array containing meta data about admin groups
75
+     * [1] array containing meta data about unprivileged groups
76
+     * @param string $groupSearch only effective when instance was created with
77
+     * isAdmin being true
78
+     * @param string $userSearch the pattern users are search for
79
+     * @return array
80
+     */
81
+    public function get($groupSearch = '', $userSearch = '') {
82
+        $key = $groupSearch . '::' . $userSearch;
83
+        if(isset($this->metaData[$key])) {
84
+            return $this->metaData[$key];
85
+        }
86
+
87
+        $adminGroups = array();
88
+        $groups = array();
89
+        $sortGroupsIndex = 0;
90
+        $sortGroupsKeys = array();
91
+        $sortAdminGroupsIndex = 0;
92
+        $sortAdminGroupsKeys = array();
93
+
94
+        foreach($this->getGroups($groupSearch) as $group) {
95
+            $groupMetaData = $this->generateGroupMetaData($group, $userSearch);
96
+            if (strtolower($group->getGID()) !== 'admin') {
97
+                $this->addEntry(
98
+                    $groups,
99
+                    $sortGroupsKeys,
100
+                    $sortGroupsIndex,
101
+                    $groupMetaData);
102
+            } else {
103
+                //admin group is hard coded to 'admin' for now. In future,
104
+                //backends may define admin groups too. Then the if statement
105
+                //has to be adjusted accordingly.
106
+                $this->addEntry(
107
+                    $adminGroups,
108
+                    $sortAdminGroupsKeys,
109
+                    $sortAdminGroupsIndex,
110
+                    $groupMetaData);
111
+            }
112
+        }
113
+
114
+        //whether sorting is necessary is will be checked in sort()
115
+        $this->sort($groups, $sortGroupsKeys);
116
+        $this->sort($adminGroups, $sortAdminGroupsKeys);
117
+
118
+        $this->metaData[$key] = array($adminGroups, $groups);
119
+        return $this->metaData[$key];
120
+    }
121
+
122
+    /**
123
+     * sets the sort mode, see SORT_* constants for supported modes
124
+     *
125
+     * @param int $sortMode
126
+     */
127
+    public function setSorting($sortMode) {
128
+        switch ($sortMode) {
129
+            case self::SORT_USERCOUNT:
130
+            case self::SORT_GROUPNAME:
131
+                $this->sorting = $sortMode;
132
+                break;
133
+
134
+            default:
135
+                $this->sorting = self::SORT_NONE;
136
+        }
137
+    }
138
+
139
+    /**
140
+     * adds an group entry to the resulting array
141
+     * @param array $entries the resulting array, by reference
142
+     * @param array $sortKeys the sort key array, by reference
143
+     * @param int $sortIndex the sort key index, by reference
144
+     * @param array $data the group's meta data as returned by generateGroupMetaData()
145
+     */
146
+    private function addEntry(&$entries, &$sortKeys, &$sortIndex, $data) {
147
+        $entries[] = $data;
148
+        if ($this->sorting === self::SORT_USERCOUNT) {
149
+            $sortKeys[$sortIndex] = $data['usercount'];
150
+            $sortIndex++;
151
+        } else if ($this->sorting === self::SORT_GROUPNAME) {
152
+            $sortKeys[$sortIndex] = $data['name'];
153
+            $sortIndex++;
154
+        }
155
+    }
156
+
157
+    /**
158
+     * creates an array containing the group meta data
159
+     * @param \OCP\IGroup $group
160
+     * @param string $userSearch
161
+     * @return array with the keys 'id', 'name', 'usercount' and 'disabled'
162
+     */
163
+    private function generateGroupMetaData(\OCP\IGroup $group, $userSearch) {
164
+        return array(
165
+                'id' => $group->getGID(),
166
+                'name' => $group->getDisplayName(),
167
+                'usercount' => $this->sorting === self::SORT_USERCOUNT ? $group->count($userSearch) : 0,
168
+                'disabled' => $group->countDisabled()
169
+            );
170
+    }
171
+
172
+    /**
173
+     * sorts the result array, if applicable
174
+     * @param array $entries the result array, by reference
175
+     * @param array $sortKeys the array containing the sort keys
176
+     * @param return null
177
+     */
178
+    private function sort(&$entries, $sortKeys) {
179
+        if ($this->sorting === self::SORT_USERCOUNT) {
180
+            array_multisort($sortKeys, SORT_DESC, $entries);
181
+        } else if ($this->sorting === self::SORT_GROUPNAME) {
182
+            array_multisort($sortKeys, SORT_ASC, $entries);
183
+        }
184
+    }
185
+
186
+    /**
187
+     * returns the available groups
188
+     * @param string $search a search string
189
+     * @return \OCP\IGroup[]
190
+     */
191
+    public function getGroups($search = '') {
192
+        if($this->isAdmin) {
193
+            return $this->groupManager->search($search);
194
+        } else {
195
+            $userObject = $this->userSession->getUser();
196
+            if($userObject !== null) {
197
+                $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($userObject);
198
+            } else {
199
+                $groups = [];
200
+            }
201
+
202
+            return $groups;
203
+        }
204
+    }
205 205
 }
Please login to merge, or discard this patch.
lib/private/User/Manager.php 1 patch
Indentation   +533 added lines, -533 removed lines patch added patch discarded remove patch
@@ -58,541 +58,541 @@
 block discarded – undo
58 58
  * @package OC\User
59 59
  */
60 60
 class Manager extends PublicEmitter implements IUserManager {
61
-	/**
62
-	 * @var \OCP\UserInterface[] $backends
63
-	 */
64
-	private $backends = array();
65
-
66
-	/**
67
-	 * @var \OC\User\User[] $cachedUsers
68
-	 */
69
-	private $cachedUsers = array();
70
-
71
-	/**
72
-	 * @var \OCP\IConfig $config
73
-	 */
74
-	private $config;
75
-
76
-	/**
77
-	 * @param \OCP\IConfig $config
78
-	 */
79
-	public function __construct(IConfig $config) {
80
-		$this->config = $config;
81
-		$cachedUsers = &$this->cachedUsers;
82
-		$this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
83
-			/** @var \OC\User\User $user */
84
-			unset($cachedUsers[$user->getUID()]);
85
-		});
86
-	}
87
-
88
-	/**
89
-	 * Get the active backends
90
-	 * @return \OCP\UserInterface[]
91
-	 */
92
-	public function getBackends() {
93
-		return $this->backends;
94
-	}
95
-
96
-	/**
97
-	 * register a user backend
98
-	 *
99
-	 * @param \OCP\UserInterface $backend
100
-	 */
101
-	public function registerBackend($backend) {
102
-		$this->backends[] = $backend;
103
-	}
104
-
105
-	/**
106
-	 * remove a user backend
107
-	 *
108
-	 * @param \OCP\UserInterface $backend
109
-	 */
110
-	public function removeBackend($backend) {
111
-		$this->cachedUsers = array();
112
-		if (($i = array_search($backend, $this->backends)) !== false) {
113
-			unset($this->backends[$i]);
114
-		}
115
-	}
116
-
117
-	/**
118
-	 * remove all user backends
119
-	 */
120
-	public function clearBackends() {
121
-		$this->cachedUsers = array();
122
-		$this->backends = array();
123
-	}
124
-
125
-	/**
126
-	 * get a user by user id
127
-	 *
128
-	 * @param string $uid
129
-	 * @return \OC\User\User|null Either the user or null if the specified user does not exist
130
-	 */
131
-	public function get($uid) {
132
-		if (is_null($uid) || $uid === '' || $uid === false) {
133
-			return null;
134
-		}
135
-		if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
136
-			return $this->cachedUsers[$uid];
137
-		}
138
-		foreach ($this->backends as $backend) {
139
-			if ($backend->userExists($uid)) {
140
-				return $this->getUserObject($uid, $backend);
141
-			}
142
-		}
143
-		return null;
144
-	}
145
-
146
-	/**
147
-	 * get or construct the user object
148
-	 *
149
-	 * @param string $uid
150
-	 * @param \OCP\UserInterface $backend
151
-	 * @param bool $cacheUser If false the newly created user object will not be cached
152
-	 * @return \OC\User\User
153
-	 */
154
-	protected function getUserObject($uid, $backend, $cacheUser = true) {
155
-		if (isset($this->cachedUsers[$uid])) {
156
-			return $this->cachedUsers[$uid];
157
-		}
158
-
159
-		$user = new User($uid, $backend, $this, $this->config);
160
-		if ($cacheUser) {
161
-			$this->cachedUsers[$uid] = $user;
162
-		}
163
-		return $user;
164
-	}
165
-
166
-	/**
167
-	 * check if a user exists
168
-	 *
169
-	 * @param string $uid
170
-	 * @return bool
171
-	 */
172
-	public function userExists($uid) {
173
-		$user = $this->get($uid);
174
-		return ($user !== null);
175
-	}
176
-
177
-	/**
178
-	 * Check if the password is valid for the user
179
-	 *
180
-	 * @param string $loginName
181
-	 * @param string $password
182
-	 * @return mixed the User object on success, false otherwise
183
-	 */
184
-	public function checkPassword($loginName, $password) {
185
-		$result = $this->checkPasswordNoLogging($loginName, $password);
186
-
187
-		if ($result === false) {
188
-			\OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
189
-		}
190
-
191
-		return $result;
192
-	}
193
-
194
-	/**
195
-	 * Check if the password is valid for the user
196
-	 *
197
-	 * @internal
198
-	 * @param string $loginName
199
-	 * @param string $password
200
-	 * @return mixed the User object on success, false otherwise
201
-	 */
202
-	public function checkPasswordNoLogging($loginName, $password) {
203
-		$loginName = str_replace("\0", '', $loginName);
204
-		$password = str_replace("\0", '', $password);
205
-
206
-		foreach ($this->backends as $backend) {
207
-			if ($backend->implementsActions(Backend::CHECK_PASSWORD)) {
208
-				$uid = $backend->checkPassword($loginName, $password);
209
-				if ($uid !== false) {
210
-					return $this->getUserObject($uid, $backend);
211
-				}
212
-			}
213
-		}
214
-
215
-		return false;
216
-	}
217
-
218
-	/**
219
-	 * search by user id
220
-	 *
221
-	 * @param string $pattern
222
-	 * @param int $limit
223
-	 * @param int $offset
224
-	 * @return \OC\User\User[]
225
-	 */
226
-	public function search($pattern, $limit = null, $offset = null) {
227
-		$users = array();
228
-		foreach ($this->backends as $backend) {
229
-			$backendUsers = $backend->getUsers($pattern, $limit, $offset);
230
-			if (is_array($backendUsers)) {
231
-				foreach ($backendUsers as $uid) {
232
-					$users[$uid] = $this->getUserObject($uid, $backend);
233
-				}
234
-			}
235
-		}
236
-
237
-		uasort($users, function ($a, $b) {
238
-			/**
239
-			 * @var \OC\User\User $a
240
-			 * @var \OC\User\User $b
241
-			 */
242
-			return strcmp($a->getUID(), $b->getUID());
243
-		});
244
-		return $users;
245
-	}
246
-
247
-	/**
248
-	 * search by displayName
249
-	 *
250
-	 * @param string $pattern
251
-	 * @param int $limit
252
-	 * @param int $offset
253
-	 * @return \OC\User\User[]
254
-	 */
255
-	public function searchDisplayName($pattern, $limit = null, $offset = null) {
256
-		$users = array();
257
-		foreach ($this->backends as $backend) {
258
-			$backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
259
-			if (is_array($backendUsers)) {
260
-				foreach ($backendUsers as $uid => $displayName) {
261
-					$users[] = $this->getUserObject($uid, $backend);
262
-				}
263
-			}
264
-		}
265
-
266
-		usort($users, function ($a, $b) {
267
-			/**
268
-			 * @var \OC\User\User $a
269
-			 * @var \OC\User\User $b
270
-			 */
271
-			return strcmp(strtolower($a->getDisplayName()), strtolower($b->getDisplayName()));
272
-		});
273
-		return $users;
274
-	}
275
-
276
-	/**
277
-	 * @param string $uid
278
-	 * @param string $password
279
-	 * @throws \InvalidArgumentException
280
-	 * @return bool|IUser the created user or false
281
-	 */
282
-	public function createUser($uid, $password) {
283
-		$localBackends = [];
284
-		foreach ($this->backends as $backend) {
285
-			if ($backend instanceof Database) {
286
-				// First check if there is another user backend
287
-				$localBackends[] = $backend;
288
-				continue;
289
-			}
290
-
291
-			if ($backend->implementsActions(Backend::CREATE_USER)) {
292
-				return $this->createUserFromBackend($uid, $password, $backend);
293
-			}
294
-		}
295
-
296
-		foreach ($localBackends as $backend) {
297
-			if ($backend->implementsActions(Backend::CREATE_USER)) {
298
-				return $this->createUserFromBackend($uid, $password, $backend);
299
-			}
300
-		}
301
-
302
-		return false;
303
-	}
304
-
305
-	/**
306
-	 * @param string $uid
307
-	 * @param string $password
308
-	 * @param UserInterface $backend
309
-	 * @return IUser|null
310
-	 * @throws \InvalidArgumentException
311
-	 */
312
-	public function createUserFromBackend($uid, $password, UserInterface $backend) {
313
-		$l = \OC::$server->getL10N('lib');
314
-
315
-		// Check the name for bad characters
316
-		// Allowed are: "a-z", "A-Z", "0-9" and "_.@-'"
317
-		if (preg_match('/[^a-zA-Z0-9 _\.@\-\']/', $uid)) {
318
-			throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
319
-				. ' "a-z", "A-Z", "0-9", and "_.@-\'"'));
320
-		}
321
-		// No empty username
322
-		if (trim($uid) === '') {
323
-			throw new \InvalidArgumentException($l->t('A valid username must be provided'));
324
-		}
325
-		// No whitespace at the beginning or at the end
326
-		if (trim($uid) !== $uid) {
327
-			throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
328
-		}
329
-		// Username only consists of 1 or 2 dots (directory traversal)
330
-		if ($uid === '.' || $uid === '..') {
331
-			throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
332
-		}
333
-		// No empty password
334
-		if (trim($password) === '') {
335
-			throw new \InvalidArgumentException($l->t('A valid password must be provided'));
336
-		}
337
-
338
-		// Check if user already exists
339
-		if ($this->userExists($uid)) {
340
-			throw new \InvalidArgumentException($l->t('The username is already being used'));
341
-		}
342
-
343
-		$this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
344
-		$state = $backend->createUser($uid, $password);
345
-		if($state === false) {
346
-			throw new \InvalidArgumentException($l->t('Could not create user'));
347
-		}
348
-		$user = $this->getUserObject($uid, $backend);
349
-		if ($user instanceof IUser) {
350
-			$this->emit('\OC\User', 'postCreateUser', [$user, $password]);
351
-		}
352
-		return $user;
353
-	}
354
-
355
-	/**
356
-	 * returns how many users per backend exist (if supported by backend)
357
-	 *
358
-	 * @param boolean $hasLoggedIn when true only users that have a lastLogin
359
-	 *                entry in the preferences table will be affected
360
-	 * @return array|int an array of backend class as key and count number as value
361
-	 *                if $hasLoggedIn is true only an int is returned
362
-	 */
363
-	public function countUsers($hasLoggedIn = false) {
364
-		if ($hasLoggedIn) {
365
-			return $this->countSeenUsers();
366
-		}
367
-		$userCountStatistics = [];
368
-		foreach ($this->backends as $backend) {
369
-			if ($backend->implementsActions(Backend::COUNT_USERS)) {
370
-				$backendUsers = $backend->countUsers();
371
-				if($backendUsers !== false) {
372
-					if($backend instanceof IUserBackend) {
373
-						$name = $backend->getBackendName();
374
-					} else {
375
-						$name = get_class($backend);
376
-					}
377
-					if(isset($userCountStatistics[$name])) {
378
-						$userCountStatistics[$name] += $backendUsers;
379
-					} else {
380
-						$userCountStatistics[$name] = $backendUsers;
381
-					}
382
-				}
383
-			}
384
-		}
385
-		return $userCountStatistics;
386
-	}
387
-
388
-	/**
389
-	 * returns how many users per backend exist in the requested groups (if supported by backend)
390
-	 *
391
-	 * @param IGroup[] $groups an array of gid to search in
392
-	 * @return array|int an array of backend class as key and count number as value
393
-	 *                if $hasLoggedIn is true only an int is returned
394
-	 */
395
-	public function countUsersOfGroups(array $groups) {
396
-		$users = [];
397
-		foreach($groups as $group) {
398
-			$usersIds = array_map(function($user) {
399
-				return $user->getUID();
400
-			}, $group->getUsers());
401
-			$users = array_merge($users, $usersIds);
402
-		}
403
-		return count(array_unique($users));
404
-	}
405
-
406
-	/**
407
-	 * The callback is executed for each user on each backend.
408
-	 * If the callback returns false no further users will be retrieved.
409
-	 *
410
-	 * @param \Closure $callback
411
-	 * @param string $search
412
-	 * @param boolean $onlySeen when true only users that have a lastLogin entry
413
-	 *                in the preferences table will be affected
414
-	 * @since 9.0.0
415
-	 */
416
-	public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
417
-		if ($onlySeen) {
418
-			$this->callForSeenUsers($callback);
419
-		} else {
420
-			foreach ($this->getBackends() as $backend) {
421
-				$limit = 500;
422
-				$offset = 0;
423
-				do {
424
-					$users = $backend->getUsers($search, $limit, $offset);
425
-					foreach ($users as $uid) {
426
-						if (!$backend->userExists($uid)) {
427
-							continue;
428
-						}
429
-						$user = $this->getUserObject($uid, $backend, false);
430
-						$return = $callback($user);
431
-						if ($return === false) {
432
-							break;
433
-						}
434
-					}
435
-					$offset += $limit;
436
-				} while (count($users) >= $limit);
437
-			}
438
-		}
439
-	}
440
-
441
-	/**
442
-	 * returns how many users are disabled
443
-	 *
444
-	 * @return int
445
-	 * @since 12.0.0
446
-	 */
447
-	public function countDisabledUsers(): int {
448
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
449
-		$queryBuilder->select($queryBuilder->createFunction('COUNT(*)'))
450
-			->from('preferences')
451
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
452
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
453
-			->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR));
61
+    /**
62
+     * @var \OCP\UserInterface[] $backends
63
+     */
64
+    private $backends = array();
65
+
66
+    /**
67
+     * @var \OC\User\User[] $cachedUsers
68
+     */
69
+    private $cachedUsers = array();
70
+
71
+    /**
72
+     * @var \OCP\IConfig $config
73
+     */
74
+    private $config;
75
+
76
+    /**
77
+     * @param \OCP\IConfig $config
78
+     */
79
+    public function __construct(IConfig $config) {
80
+        $this->config = $config;
81
+        $cachedUsers = &$this->cachedUsers;
82
+        $this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
83
+            /** @var \OC\User\User $user */
84
+            unset($cachedUsers[$user->getUID()]);
85
+        });
86
+    }
87
+
88
+    /**
89
+     * Get the active backends
90
+     * @return \OCP\UserInterface[]
91
+     */
92
+    public function getBackends() {
93
+        return $this->backends;
94
+    }
95
+
96
+    /**
97
+     * register a user backend
98
+     *
99
+     * @param \OCP\UserInterface $backend
100
+     */
101
+    public function registerBackend($backend) {
102
+        $this->backends[] = $backend;
103
+    }
104
+
105
+    /**
106
+     * remove a user backend
107
+     *
108
+     * @param \OCP\UserInterface $backend
109
+     */
110
+    public function removeBackend($backend) {
111
+        $this->cachedUsers = array();
112
+        if (($i = array_search($backend, $this->backends)) !== false) {
113
+            unset($this->backends[$i]);
114
+        }
115
+    }
116
+
117
+    /**
118
+     * remove all user backends
119
+     */
120
+    public function clearBackends() {
121
+        $this->cachedUsers = array();
122
+        $this->backends = array();
123
+    }
124
+
125
+    /**
126
+     * get a user by user id
127
+     *
128
+     * @param string $uid
129
+     * @return \OC\User\User|null Either the user or null if the specified user does not exist
130
+     */
131
+    public function get($uid) {
132
+        if (is_null($uid) || $uid === '' || $uid === false) {
133
+            return null;
134
+        }
135
+        if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
136
+            return $this->cachedUsers[$uid];
137
+        }
138
+        foreach ($this->backends as $backend) {
139
+            if ($backend->userExists($uid)) {
140
+                return $this->getUserObject($uid, $backend);
141
+            }
142
+        }
143
+        return null;
144
+    }
145
+
146
+    /**
147
+     * get or construct the user object
148
+     *
149
+     * @param string $uid
150
+     * @param \OCP\UserInterface $backend
151
+     * @param bool $cacheUser If false the newly created user object will not be cached
152
+     * @return \OC\User\User
153
+     */
154
+    protected function getUserObject($uid, $backend, $cacheUser = true) {
155
+        if (isset($this->cachedUsers[$uid])) {
156
+            return $this->cachedUsers[$uid];
157
+        }
158
+
159
+        $user = new User($uid, $backend, $this, $this->config);
160
+        if ($cacheUser) {
161
+            $this->cachedUsers[$uid] = $user;
162
+        }
163
+        return $user;
164
+    }
165
+
166
+    /**
167
+     * check if a user exists
168
+     *
169
+     * @param string $uid
170
+     * @return bool
171
+     */
172
+    public function userExists($uid) {
173
+        $user = $this->get($uid);
174
+        return ($user !== null);
175
+    }
176
+
177
+    /**
178
+     * Check if the password is valid for the user
179
+     *
180
+     * @param string $loginName
181
+     * @param string $password
182
+     * @return mixed the User object on success, false otherwise
183
+     */
184
+    public function checkPassword($loginName, $password) {
185
+        $result = $this->checkPasswordNoLogging($loginName, $password);
186
+
187
+        if ($result === false) {
188
+            \OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
189
+        }
190
+
191
+        return $result;
192
+    }
193
+
194
+    /**
195
+     * Check if the password is valid for the user
196
+     *
197
+     * @internal
198
+     * @param string $loginName
199
+     * @param string $password
200
+     * @return mixed the User object on success, false otherwise
201
+     */
202
+    public function checkPasswordNoLogging($loginName, $password) {
203
+        $loginName = str_replace("\0", '', $loginName);
204
+        $password = str_replace("\0", '', $password);
205
+
206
+        foreach ($this->backends as $backend) {
207
+            if ($backend->implementsActions(Backend::CHECK_PASSWORD)) {
208
+                $uid = $backend->checkPassword($loginName, $password);
209
+                if ($uid !== false) {
210
+                    return $this->getUserObject($uid, $backend);
211
+                }
212
+            }
213
+        }
214
+
215
+        return false;
216
+    }
217
+
218
+    /**
219
+     * search by user id
220
+     *
221
+     * @param string $pattern
222
+     * @param int $limit
223
+     * @param int $offset
224
+     * @return \OC\User\User[]
225
+     */
226
+    public function search($pattern, $limit = null, $offset = null) {
227
+        $users = array();
228
+        foreach ($this->backends as $backend) {
229
+            $backendUsers = $backend->getUsers($pattern, $limit, $offset);
230
+            if (is_array($backendUsers)) {
231
+                foreach ($backendUsers as $uid) {
232
+                    $users[$uid] = $this->getUserObject($uid, $backend);
233
+                }
234
+            }
235
+        }
236
+
237
+        uasort($users, function ($a, $b) {
238
+            /**
239
+             * @var \OC\User\User $a
240
+             * @var \OC\User\User $b
241
+             */
242
+            return strcmp($a->getUID(), $b->getUID());
243
+        });
244
+        return $users;
245
+    }
246
+
247
+    /**
248
+     * search by displayName
249
+     *
250
+     * @param string $pattern
251
+     * @param int $limit
252
+     * @param int $offset
253
+     * @return \OC\User\User[]
254
+     */
255
+    public function searchDisplayName($pattern, $limit = null, $offset = null) {
256
+        $users = array();
257
+        foreach ($this->backends as $backend) {
258
+            $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
259
+            if (is_array($backendUsers)) {
260
+                foreach ($backendUsers as $uid => $displayName) {
261
+                    $users[] = $this->getUserObject($uid, $backend);
262
+                }
263
+            }
264
+        }
265
+
266
+        usort($users, function ($a, $b) {
267
+            /**
268
+             * @var \OC\User\User $a
269
+             * @var \OC\User\User $b
270
+             */
271
+            return strcmp(strtolower($a->getDisplayName()), strtolower($b->getDisplayName()));
272
+        });
273
+        return $users;
274
+    }
275
+
276
+    /**
277
+     * @param string $uid
278
+     * @param string $password
279
+     * @throws \InvalidArgumentException
280
+     * @return bool|IUser the created user or false
281
+     */
282
+    public function createUser($uid, $password) {
283
+        $localBackends = [];
284
+        foreach ($this->backends as $backend) {
285
+            if ($backend instanceof Database) {
286
+                // First check if there is another user backend
287
+                $localBackends[] = $backend;
288
+                continue;
289
+            }
290
+
291
+            if ($backend->implementsActions(Backend::CREATE_USER)) {
292
+                return $this->createUserFromBackend($uid, $password, $backend);
293
+            }
294
+        }
295
+
296
+        foreach ($localBackends as $backend) {
297
+            if ($backend->implementsActions(Backend::CREATE_USER)) {
298
+                return $this->createUserFromBackend($uid, $password, $backend);
299
+            }
300
+        }
301
+
302
+        return false;
303
+    }
304
+
305
+    /**
306
+     * @param string $uid
307
+     * @param string $password
308
+     * @param UserInterface $backend
309
+     * @return IUser|null
310
+     * @throws \InvalidArgumentException
311
+     */
312
+    public function createUserFromBackend($uid, $password, UserInterface $backend) {
313
+        $l = \OC::$server->getL10N('lib');
314
+
315
+        // Check the name for bad characters
316
+        // Allowed are: "a-z", "A-Z", "0-9" and "_.@-'"
317
+        if (preg_match('/[^a-zA-Z0-9 _\.@\-\']/', $uid)) {
318
+            throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
319
+                . ' "a-z", "A-Z", "0-9", and "_.@-\'"'));
320
+        }
321
+        // No empty username
322
+        if (trim($uid) === '') {
323
+            throw new \InvalidArgumentException($l->t('A valid username must be provided'));
324
+        }
325
+        // No whitespace at the beginning or at the end
326
+        if (trim($uid) !== $uid) {
327
+            throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
328
+        }
329
+        // Username only consists of 1 or 2 dots (directory traversal)
330
+        if ($uid === '.' || $uid === '..') {
331
+            throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
332
+        }
333
+        // No empty password
334
+        if (trim($password) === '') {
335
+            throw new \InvalidArgumentException($l->t('A valid password must be provided'));
336
+        }
337
+
338
+        // Check if user already exists
339
+        if ($this->userExists($uid)) {
340
+            throw new \InvalidArgumentException($l->t('The username is already being used'));
341
+        }
342
+
343
+        $this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
344
+        $state = $backend->createUser($uid, $password);
345
+        if($state === false) {
346
+            throw new \InvalidArgumentException($l->t('Could not create user'));
347
+        }
348
+        $user = $this->getUserObject($uid, $backend);
349
+        if ($user instanceof IUser) {
350
+            $this->emit('\OC\User', 'postCreateUser', [$user, $password]);
351
+        }
352
+        return $user;
353
+    }
354
+
355
+    /**
356
+     * returns how many users per backend exist (if supported by backend)
357
+     *
358
+     * @param boolean $hasLoggedIn when true only users that have a lastLogin
359
+     *                entry in the preferences table will be affected
360
+     * @return array|int an array of backend class as key and count number as value
361
+     *                if $hasLoggedIn is true only an int is returned
362
+     */
363
+    public function countUsers($hasLoggedIn = false) {
364
+        if ($hasLoggedIn) {
365
+            return $this->countSeenUsers();
366
+        }
367
+        $userCountStatistics = [];
368
+        foreach ($this->backends as $backend) {
369
+            if ($backend->implementsActions(Backend::COUNT_USERS)) {
370
+                $backendUsers = $backend->countUsers();
371
+                if($backendUsers !== false) {
372
+                    if($backend instanceof IUserBackend) {
373
+                        $name = $backend->getBackendName();
374
+                    } else {
375
+                        $name = get_class($backend);
376
+                    }
377
+                    if(isset($userCountStatistics[$name])) {
378
+                        $userCountStatistics[$name] += $backendUsers;
379
+                    } else {
380
+                        $userCountStatistics[$name] = $backendUsers;
381
+                    }
382
+                }
383
+            }
384
+        }
385
+        return $userCountStatistics;
386
+    }
387
+
388
+    /**
389
+     * returns how many users per backend exist in the requested groups (if supported by backend)
390
+     *
391
+     * @param IGroup[] $groups an array of gid to search in
392
+     * @return array|int an array of backend class as key and count number as value
393
+     *                if $hasLoggedIn is true only an int is returned
394
+     */
395
+    public function countUsersOfGroups(array $groups) {
396
+        $users = [];
397
+        foreach($groups as $group) {
398
+            $usersIds = array_map(function($user) {
399
+                return $user->getUID();
400
+            }, $group->getUsers());
401
+            $users = array_merge($users, $usersIds);
402
+        }
403
+        return count(array_unique($users));
404
+    }
405
+
406
+    /**
407
+     * The callback is executed for each user on each backend.
408
+     * If the callback returns false no further users will be retrieved.
409
+     *
410
+     * @param \Closure $callback
411
+     * @param string $search
412
+     * @param boolean $onlySeen when true only users that have a lastLogin entry
413
+     *                in the preferences table will be affected
414
+     * @since 9.0.0
415
+     */
416
+    public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
417
+        if ($onlySeen) {
418
+            $this->callForSeenUsers($callback);
419
+        } else {
420
+            foreach ($this->getBackends() as $backend) {
421
+                $limit = 500;
422
+                $offset = 0;
423
+                do {
424
+                    $users = $backend->getUsers($search, $limit, $offset);
425
+                    foreach ($users as $uid) {
426
+                        if (!$backend->userExists($uid)) {
427
+                            continue;
428
+                        }
429
+                        $user = $this->getUserObject($uid, $backend, false);
430
+                        $return = $callback($user);
431
+                        if ($return === false) {
432
+                            break;
433
+                        }
434
+                    }
435
+                    $offset += $limit;
436
+                } while (count($users) >= $limit);
437
+            }
438
+        }
439
+    }
440
+
441
+    /**
442
+     * returns how many users are disabled
443
+     *
444
+     * @return int
445
+     * @since 12.0.0
446
+     */
447
+    public function countDisabledUsers(): int {
448
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
449
+        $queryBuilder->select($queryBuilder->createFunction('COUNT(*)'))
450
+            ->from('preferences')
451
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
452
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
453
+            ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR));
454 454
 
455 455
 		
456
-		$result = $queryBuilder->execute();
457
-		$count = $result->fetchColumn();
458
-		$result->closeCursor();
456
+        $result = $queryBuilder->execute();
457
+        $count = $result->fetchColumn();
458
+        $result->closeCursor();
459 459
 		
460
-		if ($count !== false) {
461
-			$count = (int)$count;
462
-		} else {
463
-			$count = 0;
464
-		}
465
-
466
-		return $count;
467
-	}
468
-
469
-	/**
470
-	 * returns how many users are disabled in the requested groups
471
-	 *
472
-	 * @param array $groups groupids to search
473
-	 * @return int
474
-	 * @since 14.0.0
475
-	 */
476
-	public function countDisabledUsersOfGroups(array $groups): int {
477
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
478
-		$queryBuilder->select($queryBuilder->createFunction('COUNT(Distinct uid)'))
479
-			->from('preferences', 'p')
480
-			->innerJoin('p', 'group_user', 'g', 'p.userid = g.uid')
481
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
482
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
483
-			->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
484
-			->andWhere($queryBuilder->expr()->in('gid', $queryBuilder->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
485
-
486
-		$result = $queryBuilder->execute();
487
-		$count = $result->fetchColumn();
488
-		$result->closeCursor();
460
+        if ($count !== false) {
461
+            $count = (int)$count;
462
+        } else {
463
+            $count = 0;
464
+        }
465
+
466
+        return $count;
467
+    }
468
+
469
+    /**
470
+     * returns how many users are disabled in the requested groups
471
+     *
472
+     * @param array $groups groupids to search
473
+     * @return int
474
+     * @since 14.0.0
475
+     */
476
+    public function countDisabledUsersOfGroups(array $groups): int {
477
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
478
+        $queryBuilder->select($queryBuilder->createFunction('COUNT(Distinct uid)'))
479
+            ->from('preferences', 'p')
480
+            ->innerJoin('p', 'group_user', 'g', 'p.userid = g.uid')
481
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
482
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
483
+            ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
484
+            ->andWhere($queryBuilder->expr()->in('gid', $queryBuilder->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
485
+
486
+        $result = $queryBuilder->execute();
487
+        $count = $result->fetchColumn();
488
+        $result->closeCursor();
489 489
 		
490
-		if ($count !== false) {
491
-			$count = (int)$count;
492
-		} else {
493
-			$count = 0;
494
-		}
495
-
496
-		return $count;
497
-	}
498
-
499
-	/**
500
-	 * returns how many users have logged in once
501
-	 *
502
-	 * @return int
503
-	 * @since 11.0.0
504
-	 */
505
-	public function countSeenUsers() {
506
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
507
-		$queryBuilder->select($queryBuilder->createFunction('COUNT(*)'))
508
-			->from('preferences')
509
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
510
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')))
511
-			->andWhere($queryBuilder->expr()->isNotNull('configvalue'));
512
-
513
-		$query = $queryBuilder->execute();
514
-
515
-		$result = (int)$query->fetchColumn();
516
-		$query->closeCursor();
517
-
518
-		return $result;
519
-	}
520
-
521
-	/**
522
-	 * @param \Closure $callback
523
-	 * @since 11.0.0
524
-	 */
525
-	public function callForSeenUsers(\Closure $callback) {
526
-		$limit = 1000;
527
-		$offset = 0;
528
-		do {
529
-			$userIds = $this->getSeenUserIds($limit, $offset);
530
-			$offset += $limit;
531
-			foreach ($userIds as $userId) {
532
-				foreach ($this->backends as $backend) {
533
-					if ($backend->userExists($userId)) {
534
-						$user = $this->getUserObject($userId, $backend, false);
535
-						$return = $callback($user);
536
-						if ($return === false) {
537
-							return;
538
-						}
539
-						break;
540
-					}
541
-				}
542
-			}
543
-		} while (count($userIds) >= $limit);
544
-	}
545
-
546
-	/**
547
-	 * Getting all userIds that have a listLogin value requires checking the
548
-	 * value in php because on oracle you cannot use a clob in a where clause,
549
-	 * preventing us from doing a not null or length(value) > 0 check.
550
-	 *
551
-	 * @param int $limit
552
-	 * @param int $offset
553
-	 * @return string[] with user ids
554
-	 */
555
-	private function getSeenUserIds($limit = null, $offset = null) {
556
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
557
-		$queryBuilder->select(['userid'])
558
-			->from('preferences')
559
-			->where($queryBuilder->expr()->eq(
560
-				'appid', $queryBuilder->createNamedParameter('login'))
561
-			)
562
-			->andWhere($queryBuilder->expr()->eq(
563
-				'configkey', $queryBuilder->createNamedParameter('lastLogin'))
564
-			)
565
-			->andWhere($queryBuilder->expr()->isNotNull('configvalue')
566
-			);
567
-
568
-		if ($limit !== null) {
569
-			$queryBuilder->setMaxResults($limit);
570
-		}
571
-		if ($offset !== null) {
572
-			$queryBuilder->setFirstResult($offset);
573
-		}
574
-		$query = $queryBuilder->execute();
575
-		$result = [];
576
-
577
-		while ($row = $query->fetch()) {
578
-			$result[] = $row['userid'];
579
-		}
580
-
581
-		$query->closeCursor();
582
-
583
-		return $result;
584
-	}
585
-
586
-	/**
587
-	 * @param string $email
588
-	 * @return IUser[]
589
-	 * @since 9.1.0
590
-	 */
591
-	public function getByEmail($email) {
592
-		$userIds = $this->config->getUsersForUserValue('settings', 'email', $email);
593
-
594
-		return array_map(function($uid) {
595
-			return $this->get($uid);
596
-		}, $userIds);
597
-	}
490
+        if ($count !== false) {
491
+            $count = (int)$count;
492
+        } else {
493
+            $count = 0;
494
+        }
495
+
496
+        return $count;
497
+    }
498
+
499
+    /**
500
+     * returns how many users have logged in once
501
+     *
502
+     * @return int
503
+     * @since 11.0.0
504
+     */
505
+    public function countSeenUsers() {
506
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
507
+        $queryBuilder->select($queryBuilder->createFunction('COUNT(*)'))
508
+            ->from('preferences')
509
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
510
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')))
511
+            ->andWhere($queryBuilder->expr()->isNotNull('configvalue'));
512
+
513
+        $query = $queryBuilder->execute();
514
+
515
+        $result = (int)$query->fetchColumn();
516
+        $query->closeCursor();
517
+
518
+        return $result;
519
+    }
520
+
521
+    /**
522
+     * @param \Closure $callback
523
+     * @since 11.0.0
524
+     */
525
+    public function callForSeenUsers(\Closure $callback) {
526
+        $limit = 1000;
527
+        $offset = 0;
528
+        do {
529
+            $userIds = $this->getSeenUserIds($limit, $offset);
530
+            $offset += $limit;
531
+            foreach ($userIds as $userId) {
532
+                foreach ($this->backends as $backend) {
533
+                    if ($backend->userExists($userId)) {
534
+                        $user = $this->getUserObject($userId, $backend, false);
535
+                        $return = $callback($user);
536
+                        if ($return === false) {
537
+                            return;
538
+                        }
539
+                        break;
540
+                    }
541
+                }
542
+            }
543
+        } while (count($userIds) >= $limit);
544
+    }
545
+
546
+    /**
547
+     * Getting all userIds that have a listLogin value requires checking the
548
+     * value in php because on oracle you cannot use a clob in a where clause,
549
+     * preventing us from doing a not null or length(value) > 0 check.
550
+     *
551
+     * @param int $limit
552
+     * @param int $offset
553
+     * @return string[] with user ids
554
+     */
555
+    private function getSeenUserIds($limit = null, $offset = null) {
556
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
557
+        $queryBuilder->select(['userid'])
558
+            ->from('preferences')
559
+            ->where($queryBuilder->expr()->eq(
560
+                'appid', $queryBuilder->createNamedParameter('login'))
561
+            )
562
+            ->andWhere($queryBuilder->expr()->eq(
563
+                'configkey', $queryBuilder->createNamedParameter('lastLogin'))
564
+            )
565
+            ->andWhere($queryBuilder->expr()->isNotNull('configvalue')
566
+            );
567
+
568
+        if ($limit !== null) {
569
+            $queryBuilder->setMaxResults($limit);
570
+        }
571
+        if ($offset !== null) {
572
+            $queryBuilder->setFirstResult($offset);
573
+        }
574
+        $query = $queryBuilder->execute();
575
+        $result = [];
576
+
577
+        while ($row = $query->fetch()) {
578
+            $result[] = $row['userid'];
579
+        }
580
+
581
+        $query->closeCursor();
582
+
583
+        return $result;
584
+    }
585
+
586
+    /**
587
+     * @param string $email
588
+     * @return IUser[]
589
+     * @since 9.1.0
590
+     */
591
+    public function getByEmail($email) {
592
+        $userIds = $this->config->getUsersForUserValue('settings', 'email', $email);
593
+
594
+        return array_map(function($uid) {
595
+            return $this->get($uid);
596
+        }, $userIds);
597
+    }
598 598
 }
Please login to merge, or discard this patch.