Passed
Push — master ( b83432...1f4dd6 )
by Robin
27:45 queued 09:54
created
lib/public/GroupInterface.php 1 patch
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -36,85 +36,85 @@
 block discarded – undo
36 36
  * @since 4.5.0
37 37
  */
38 38
 interface GroupInterface {
39
-	/**
40
-	 * actions that user backends can define
41
-	 */
42
-	public const CREATE_GROUP = 0x00000001;
43
-	public const DELETE_GROUP = 0x00000010;
44
-	public const ADD_TO_GROUP = 0x00000100;
45
-	public const REMOVE_FROM_GOUP = 0x00001000; // oops
46
-	public const REMOVE_FROM_GROUP = 0x00001000;
47
-	//OBSOLETE const GET_DISPLAYNAME	= 0x00010000;
48
-	public const COUNT_USERS = 0x00100000;
49
-	public const GROUP_DETAILS = 0x01000000;
50
-	/**
51
-	 * @since 13.0.0
52
-	 */
53
-	public const IS_ADMIN = 0x10000000;
39
+    /**
40
+     * actions that user backends can define
41
+     */
42
+    public const CREATE_GROUP = 0x00000001;
43
+    public const DELETE_GROUP = 0x00000010;
44
+    public const ADD_TO_GROUP = 0x00000100;
45
+    public const REMOVE_FROM_GOUP = 0x00001000; // oops
46
+    public const REMOVE_FROM_GROUP = 0x00001000;
47
+    //OBSOLETE const GET_DISPLAYNAME	= 0x00010000;
48
+    public const COUNT_USERS = 0x00100000;
49
+    public const GROUP_DETAILS = 0x01000000;
50
+    /**
51
+     * @since 13.0.0
52
+     */
53
+    public const IS_ADMIN = 0x10000000;
54 54
 
55
-	/**
56
-	 * Check if backend implements actions
57
-	 * @param int $actions bitwise-or'ed actions
58
-	 * @return boolean
59
-	 * @since 4.5.0
60
-	 *
61
-	 * Returns the supported actions as int to be
62
-	 * compared with \OC_Group_Backend::CREATE_GROUP etc.
63
-	 */
64
-	public function implementsActions($actions);
55
+    /**
56
+     * Check if backend implements actions
57
+     * @param int $actions bitwise-or'ed actions
58
+     * @return boolean
59
+     * @since 4.5.0
60
+     *
61
+     * Returns the supported actions as int to be
62
+     * compared with \OC_Group_Backend::CREATE_GROUP etc.
63
+     */
64
+    public function implementsActions($actions);
65 65
 
66
-	/**
67
-	 * is user in group?
68
-	 * @param string $uid uid of the user
69
-	 * @param string $gid gid of the group
70
-	 * @return bool
71
-	 * @since 4.5.0
72
-	 *
73
-	 * Checks whether the user is member of a group or not.
74
-	 */
75
-	public function inGroup($uid, $gid);
66
+    /**
67
+     * is user in group?
68
+     * @param string $uid uid of the user
69
+     * @param string $gid gid of the group
70
+     * @return bool
71
+     * @since 4.5.0
72
+     *
73
+     * Checks whether the user is member of a group or not.
74
+     */
75
+    public function inGroup($uid, $gid);
76 76
 
77
-	/**
78
-	 * Get all groups a user belongs to
79
-	 * @param string $uid Name of the user
80
-	 * @return array an array of group names
81
-	 * @since 4.5.0
82
-	 *
83
-	 * This function fetches all groups a user belongs to. It does not check
84
-	 * if the user exists at all.
85
-	 */
86
-	public function getUserGroups($uid);
77
+    /**
78
+     * Get all groups a user belongs to
79
+     * @param string $uid Name of the user
80
+     * @return array an array of group names
81
+     * @since 4.5.0
82
+     *
83
+     * This function fetches all groups a user belongs to. It does not check
84
+     * if the user exists at all.
85
+     */
86
+    public function getUserGroups($uid);
87 87
 
88
-	/**
89
-	 * get a list of all groups
90
-	 * @param string $search
91
-	 * @param int $limit
92
-	 * @param int $offset
93
-	 * @return array an array of group names
94
-	 * @since 4.5.0
95
-	 *
96
-	 * Returns a list with all groups
97
-	 */
98
-	public function getGroups(string $search = '', int $limit = -1, int $offset = 0);
88
+    /**
89
+     * get a list of all groups
90
+     * @param string $search
91
+     * @param int $limit
92
+     * @param int $offset
93
+     * @return array an array of group names
94
+     * @since 4.5.0
95
+     *
96
+     * Returns a list with all groups
97
+     */
98
+    public function getGroups(string $search = '', int $limit = -1, int $offset = 0);
99 99
 
100
-	/**
101
-	 * check if a group exists
102
-	 * @param string $gid
103
-	 * @return bool
104
-	 * @since 4.5.0
105
-	 */
106
-	public function groupExists($gid);
100
+    /**
101
+     * check if a group exists
102
+     * @param string $gid
103
+     * @return bool
104
+     * @since 4.5.0
105
+     */
106
+    public function groupExists($gid);
107 107
 
108
-	/**
109
-	 * @brief Get a list of user ids in a group matching the given search parameters.
110
-	 *
111
-	 * @param string $gid
112
-	 * @param string $search
113
-	 * @param int $limit
114
-	 * @param int $offset
115
-	 * @return array<int,string> an array of user ids
116
-	 * @since 4.5.0
117
-	 * @deprecated 27.0.0 Use searchInGroup instead, for performance reasons
118
-	 */
119
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0);
108
+    /**
109
+     * @brief Get a list of user ids in a group matching the given search parameters.
110
+     *
111
+     * @param string $gid
112
+     * @param string $search
113
+     * @param int $limit
114
+     * @param int $offset
115
+     * @return array<int,string> an array of user ids
116
+     * @since 4.5.0
117
+     * @deprecated 27.0.0 Use searchInGroup instead, for performance reasons
118
+     */
119
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0);
120 120
 }
Please login to merge, or discard this patch.
lib/public/IGroupManager.php 1 patch
Indentation   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -46,113 +46,113 @@
 block discarded – undo
46 46
  * @since 8.0.0
47 47
  */
48 48
 interface IGroupManager {
49
-	/**
50
-	 * Checks whether a given backend is used
51
-	 *
52
-	 * @param string $backendClass Full classname including complete namespace
53
-	 * @return bool
54
-	 * @since 8.1.0
55
-	 */
56
-	public function isBackendUsed($backendClass);
49
+    /**
50
+     * Checks whether a given backend is used
51
+     *
52
+     * @param string $backendClass Full classname including complete namespace
53
+     * @return bool
54
+     * @since 8.1.0
55
+     */
56
+    public function isBackendUsed($backendClass);
57 57
 
58
-	/**
59
-	 * @param \OCP\GroupInterface $backend
60
-	 * @since 8.0.0
61
-	 */
62
-	public function addBackend($backend);
58
+    /**
59
+     * @param \OCP\GroupInterface $backend
60
+     * @since 8.0.0
61
+     */
62
+    public function addBackend($backend);
63 63
 
64
-	/**
65
-	 * @since 8.0.0
66
-	 */
67
-	public function clearBackends();
64
+    /**
65
+     * @since 8.0.0
66
+     */
67
+    public function clearBackends();
68 68
 
69
-	/**
70
-	 * Get the active backends
71
-	 * @return \OCP\GroupInterface[]
72
-	 * @since 13.0.0
73
-	 */
74
-	public function getBackends();
69
+    /**
70
+     * Get the active backends
71
+     * @return \OCP\GroupInterface[]
72
+     * @since 13.0.0
73
+     */
74
+    public function getBackends();
75 75
 
76
-	/**
77
-	 * @param string $gid
78
-	 * @return \OCP\IGroup|null
79
-	 * @since 8.0.0
80
-	 */
81
-	public function get($gid);
76
+    /**
77
+     * @param string $gid
78
+     * @return \OCP\IGroup|null
79
+     * @since 8.0.0
80
+     */
81
+    public function get($gid);
82 82
 
83
-	/**
84
-	 * @param string $gid
85
-	 * @return bool
86
-	 * @since 8.0.0
87
-	 */
88
-	public function groupExists($gid);
83
+    /**
84
+     * @param string $gid
85
+     * @return bool
86
+     * @since 8.0.0
87
+     */
88
+    public function groupExists($gid);
89 89
 
90
-	/**
91
-	 * @param string $gid
92
-	 * @return \OCP\IGroup|null
93
-	 * @since 8.0.0
94
-	 */
95
-	public function createGroup($gid);
90
+    /**
91
+     * @param string $gid
92
+     * @return \OCP\IGroup|null
93
+     * @since 8.0.0
94
+     */
95
+    public function createGroup($gid);
96 96
 
97
-	/**
98
-	 * @param string $search
99
-	 * @param ?int $limit
100
-	 * @param ?int $offset
101
-	 * @return \OCP\IGroup[]
102
-	 * @since 8.0.0
103
-	 */
104
-	public function search(string $search, ?int $limit = null, ?int $offset = 0);
97
+    /**
98
+     * @param string $search
99
+     * @param ?int $limit
100
+     * @param ?int $offset
101
+     * @return \OCP\IGroup[]
102
+     * @since 8.0.0
103
+     */
104
+    public function search(string $search, ?int $limit = null, ?int $offset = 0);
105 105
 
106
-	/**
107
-	 * @param \OCP\IUser|null $user
108
-	 * @return \OCP\IGroup[]
109
-	 * @since 8.0.0
110
-	 */
111
-	public function getUserGroups(IUser $user = null);
106
+    /**
107
+     * @param \OCP\IUser|null $user
108
+     * @return \OCP\IGroup[]
109
+     * @since 8.0.0
110
+     */
111
+    public function getUserGroups(IUser $user = null);
112 112
 
113
-	/**
114
-	 * @param \OCP\IUser $user
115
-	 * @return string[] with group names
116
-	 * @since 8.0.0
117
-	 */
118
-	public function getUserGroupIds(IUser $user): array;
113
+    /**
114
+     * @param \OCP\IUser $user
115
+     * @return string[] with group names
116
+     * @since 8.0.0
117
+     */
118
+    public function getUserGroupIds(IUser $user): array;
119 119
 
120
-	/**
121
-	 * get a list of all display names in a group
122
-	 *
123
-	 * @param string $gid
124
-	 * @param string $search
125
-	 * @param int $limit
126
-	 * @param int $offset
127
-	 * @return array an array of display names (value) and user ids (key)
128
-	 * @since 8.0.0
129
-	 */
130
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0);
120
+    /**
121
+     * get a list of all display names in a group
122
+     *
123
+     * @param string $gid
124
+     * @param string $search
125
+     * @param int $limit
126
+     * @param int $offset
127
+     * @return array an array of display names (value) and user ids (key)
128
+     * @since 8.0.0
129
+     */
130
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0);
131 131
 
132
-	/**
133
-	 * Checks if a userId is in the admin group
134
-	 * @param string $userId
135
-	 * @return bool if admin
136
-	 * @since 8.0.0
137
-	 */
138
-	public function isAdmin($userId);
132
+    /**
133
+     * Checks if a userId is in the admin group
134
+     * @param string $userId
135
+     * @return bool if admin
136
+     * @since 8.0.0
137
+     */
138
+    public function isAdmin($userId);
139 139
 
140
-	/**
141
-	 * Checks if a userId is in a group
142
-	 * @param string $userId
143
-	 * @param string $group
144
-	 * @return bool if in group
145
-	 * @since 8.0.0
146
-	 */
147
-	public function isInGroup($userId, $group);
140
+    /**
141
+     * Checks if a userId is in a group
142
+     * @param string $userId
143
+     * @param string $group
144
+     * @return bool if in group
145
+     * @since 8.0.0
146
+     */
147
+    public function isInGroup($userId, $group);
148 148
 
149
-	/**
150
-	 * Get the display name of a Nextcloud group
151
-	 *
152
-	 * @param string $groupId
153
-	 * @return ?string display name, if any
154
-	 *
155
-	 * @since 26.0.0
156
-	 */
157
-	public function getDisplayName(string $groupId): ?string;
149
+    /**
150
+     * Get the display name of a Nextcloud group
151
+     *
152
+     * @param string $groupId
153
+     * @return ?string display name, if any
154
+     *
155
+     * @since 26.0.0
156
+     */
157
+    public function getDisplayName(string $groupId): ?string;
158 158
 }
Please login to merge, or discard this patch.
lib/private/Group/Database.php 1 patch
Indentation   +466 added lines, -466 removed lines patch added patch discarded remove patch
@@ -51,470 +51,470 @@
 block discarded – undo
51 51
  * Class for group management in a SQL Database (e.g. MySQL, SQLite)
52 52
  */
53 53
 class Database extends ABackend implements
54
-	IAddToGroupBackend,
55
-	ICountDisabledInGroup,
56
-	ICountUsersBackend,
57
-	ICreateGroupBackend,
58
-	IDeleteGroupBackend,
59
-	IGetDisplayNameBackend,
60
-	IGroupDetailsBackend,
61
-	IRemoveFromGroupBackend,
62
-	ISetDisplayNameBackend,
63
-	ISearchableGroupBackend,
64
-	INamedBackend {
65
-	/** @var string[] */
66
-	private $groupCache = [];
67
-
68
-	/** @var IDBConnection */
69
-	private $dbConn;
70
-
71
-	/**
72
-	 * \OC\Group\Database constructor.
73
-	 *
74
-	 * @param IDBConnection|null $dbConn
75
-	 */
76
-	public function __construct(IDBConnection $dbConn = null) {
77
-		$this->dbConn = $dbConn;
78
-	}
79
-
80
-	/**
81
-	 * FIXME: This function should not be required!
82
-	 */
83
-	private function fixDI() {
84
-		if ($this->dbConn === null) {
85
-			$this->dbConn = \OC::$server->getDatabaseConnection();
86
-		}
87
-	}
88
-
89
-	/**
90
-	 * Try to create a new group
91
-	 * @param string $gid The name of the group to create
92
-	 * @return bool
93
-	 *
94
-	 * Tries to create a new group. If the group name already exists, false will
95
-	 * be returned.
96
-	 */
97
-	public function createGroup(string $gid): bool {
98
-		$this->fixDI();
99
-
100
-		try {
101
-			// Add group
102
-			$builder = $this->dbConn->getQueryBuilder();
103
-			$result = $builder->insert('groups')
104
-				->setValue('gid', $builder->createNamedParameter($gid))
105
-				->setValue('displayname', $builder->createNamedParameter($gid))
106
-				->execute();
107
-		} catch (UniqueConstraintViolationException $e) {
108
-			$result = 0;
109
-		}
110
-
111
-		// Add to cache
112
-		$this->groupCache[$gid] = [
113
-			'gid' => $gid,
114
-			'displayname' => $gid
115
-		];
116
-
117
-		return $result === 1;
118
-	}
119
-
120
-	/**
121
-	 * delete a group
122
-	 * @param string $gid gid of the group to delete
123
-	 * @return bool
124
-	 *
125
-	 * Deletes a group and removes it from the group_user-table
126
-	 */
127
-	public function deleteGroup(string $gid): bool {
128
-		$this->fixDI();
129
-
130
-		// Delete the group
131
-		$qb = $this->dbConn->getQueryBuilder();
132
-		$qb->delete('groups')
133
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
134
-			->execute();
135
-
136
-		// Delete the group-user relation
137
-		$qb = $this->dbConn->getQueryBuilder();
138
-		$qb->delete('group_user')
139
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
140
-			->execute();
141
-
142
-		// Delete the group-groupadmin relation
143
-		$qb = $this->dbConn->getQueryBuilder();
144
-		$qb->delete('group_admin')
145
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
146
-			->execute();
147
-
148
-		// Delete from cache
149
-		unset($this->groupCache[$gid]);
150
-
151
-		return true;
152
-	}
153
-
154
-	/**
155
-	 * is user in group?
156
-	 * @param string $uid uid of the user
157
-	 * @param string $gid gid of the group
158
-	 * @return bool
159
-	 *
160
-	 * Checks whether the user is member of a group or not.
161
-	 */
162
-	public function inGroup($uid, $gid) {
163
-		$this->fixDI();
164
-
165
-		// check
166
-		$qb = $this->dbConn->getQueryBuilder();
167
-		$cursor = $qb->select('uid')
168
-			->from('group_user')
169
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
170
-			->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
171
-			->execute();
172
-
173
-		$result = $cursor->fetch();
174
-		$cursor->closeCursor();
175
-
176
-		return $result ? true : false;
177
-	}
178
-
179
-	/**
180
-	 * Add a user to a group
181
-	 * @param string $uid Name of the user to add to group
182
-	 * @param string $gid Name of the group in which add the user
183
-	 * @return bool
184
-	 *
185
-	 * Adds a user to a group.
186
-	 */
187
-	public function addToGroup(string $uid, string $gid): bool {
188
-		$this->fixDI();
189
-
190
-		// No duplicate entries!
191
-		if (!$this->inGroup($uid, $gid)) {
192
-			$qb = $this->dbConn->getQueryBuilder();
193
-			$qb->insert('group_user')
194
-				->setValue('uid', $qb->createNamedParameter($uid))
195
-				->setValue('gid', $qb->createNamedParameter($gid))
196
-				->execute();
197
-			return true;
198
-		} else {
199
-			return false;
200
-		}
201
-	}
202
-
203
-	/**
204
-	 * Removes a user from a group
205
-	 * @param string $uid Name of the user to remove from group
206
-	 * @param string $gid Name of the group from which remove the user
207
-	 * @return bool
208
-	 *
209
-	 * removes the user from a group.
210
-	 */
211
-	public function removeFromGroup(string $uid, string $gid): bool {
212
-		$this->fixDI();
213
-
214
-		$qb = $this->dbConn->getQueryBuilder();
215
-		$qb->delete('group_user')
216
-			->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
217
-			->andWhere($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
218
-			->execute();
219
-
220
-		return true;
221
-	}
222
-
223
-	/**
224
-	 * Get all groups a user belongs to
225
-	 * @param string $uid Name of the user
226
-	 * @return array an array of group names
227
-	 *
228
-	 * This function fetches all groups a user belongs to. It does not check
229
-	 * if the user exists at all.
230
-	 */
231
-	public function getUserGroups($uid) {
232
-		//guests has empty or null $uid
233
-		if ($uid === null || $uid === '') {
234
-			return [];
235
-		}
236
-
237
-		$this->fixDI();
238
-
239
-		// No magic!
240
-		$qb = $this->dbConn->getQueryBuilder();
241
-		$cursor = $qb->select('gu.gid', 'g.displayname')
242
-			->from('group_user', 'gu')
243
-			->leftJoin('gu', 'groups', 'g', $qb->expr()->eq('gu.gid', 'g.gid'))
244
-			->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
245
-			->execute();
246
-
247
-		$groups = [];
248
-		while ($row = $cursor->fetch()) {
249
-			$groups[] = $row['gid'];
250
-			$this->groupCache[$row['gid']] = [
251
-				'gid' => $row['gid'],
252
-				'displayname' => $row['displayname'],
253
-			];
254
-		}
255
-		$cursor->closeCursor();
256
-
257
-		return $groups;
258
-	}
259
-
260
-	/**
261
-	 * get a list of all groups
262
-	 * @param string $search
263
-	 * @param int $limit
264
-	 * @param int $offset
265
-	 * @return array an array of group names
266
-	 *
267
-	 * Returns a list with all groups
268
-	 */
269
-	public function getGroups(string $search = '', int $limit = -1, int $offset = 0) {
270
-		$this->fixDI();
271
-
272
-		$query = $this->dbConn->getQueryBuilder();
273
-		$query->select('gid')
274
-			->from('groups')
275
-			->orderBy('gid', 'ASC');
276
-
277
-		if ($search !== '') {
278
-			$query->where($query->expr()->iLike('gid', $query->createNamedParameter(
279
-				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
280
-			)));
281
-			$query->orWhere($query->expr()->iLike('displayname', $query->createNamedParameter(
282
-				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
283
-			)));
284
-		}
285
-
286
-		if ($limit > 0) {
287
-			$query->setMaxResults($limit);
288
-		}
289
-		if ($offset > 0) {
290
-			$query->setFirstResult($offset);
291
-		}
292
-		$result = $query->execute();
293
-
294
-		$groups = [];
295
-		while ($row = $result->fetch()) {
296
-			$groups[] = $row['gid'];
297
-		}
298
-		$result->closeCursor();
299
-
300
-		return $groups;
301
-	}
302
-
303
-	/**
304
-	 * check if a group exists
305
-	 * @param string $gid
306
-	 * @return bool
307
-	 */
308
-	public function groupExists($gid) {
309
-		$this->fixDI();
310
-
311
-		// Check cache first
312
-		if (isset($this->groupCache[$gid])) {
313
-			return true;
314
-		}
315
-
316
-		$qb = $this->dbConn->getQueryBuilder();
317
-		$cursor = $qb->select('gid', 'displayname')
318
-			->from('groups')
319
-			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
320
-			->execute();
321
-		$result = $cursor->fetch();
322
-		$cursor->closeCursor();
323
-
324
-		if ($result !== false) {
325
-			$this->groupCache[$gid] = [
326
-				'gid' => $gid,
327
-				'displayname' => $result['displayname'],
328
-			];
329
-			return true;
330
-		}
331
-		return false;
332
-	}
333
-
334
-	/**
335
-	 * Get a list of all users in a group
336
-	 * @param string $gid
337
-	 * @param string $search
338
-	 * @param int $limit
339
-	 * @param int $offset
340
-	 * @return array<int,string> an array of user ids
341
-	 */
342
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0): array {
343
-		return array_values(array_map(fn ($user) => $user->getUid(), $this->searchInGroup($gid, $search, $limit, $offset)));
344
-	}
345
-
346
-	public function searchInGroup(string $gid, string $search = '', int $limit = -1, int $offset = 0): array {
347
-		$this->fixDI();
348
-
349
-		$query = $this->dbConn->getQueryBuilder();
350
-		$query->select('g.uid', 'u.displayname');
351
-
352
-		$query->from('group_user', 'g')
353
-			->where($query->expr()->eq('gid', $query->createNamedParameter($gid)))
354
-			->orderBy('g.uid', 'ASC');
355
-
356
-		$query->leftJoin('g', 'users', 'u', $query->expr()->eq('g.uid', 'u.uid'));
357
-
358
-		if ($search !== '') {
359
-			$query->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
360
-				$query->expr()->eq('p.userid', 'u.uid'),
361
-				$query->expr()->eq('p.appid', $query->expr()->literal('settings')),
362
-				$query->expr()->eq('p.configkey', $query->expr()->literal('email'))
363
-			))
364
-				// sqlite doesn't like re-using a single named parameter here
365
-				->andWhere(
366
-					$query->expr()->orX(
367
-						$query->expr()->ilike('g.uid', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')),
368
-						$query->expr()->ilike('u.displayname', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')),
369
-						$query->expr()->ilike('p.configvalue', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%'))
370
-					)
371
-				)
372
-				->orderBy('u.uid_lower', 'ASC');
373
-		}
374
-
375
-		if ($limit !== -1) {
376
-			$query->setMaxResults($limit);
377
-		}
378
-		if ($offset !== 0) {
379
-			$query->setFirstResult($offset);
380
-		}
381
-
382
-		$result = $query->executeQuery();
383
-
384
-		$users = [];
385
-		$userManager = \OCP\Server::get(IUserManager::class);
386
-		while ($row = $result->fetch()) {
387
-			$users[$row['uid']] = new LazyUser($row['uid'], $userManager, $row['displayname'] ?? null);
388
-		}
389
-		$result->closeCursor();
390
-
391
-		return $users;
392
-	}
393
-
394
-	/**
395
-	 * get the number of all users matching the search string in a group
396
-	 * @param string $gid
397
-	 * @param string $search
398
-	 * @return int
399
-	 */
400
-	public function countUsersInGroup(string $gid, string $search = ''): int {
401
-		$this->fixDI();
402
-
403
-		$query = $this->dbConn->getQueryBuilder();
404
-		$query->select($query->func()->count('*', 'num_users'))
405
-			->from('group_user')
406
-			->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
407
-
408
-		if ($search !== '') {
409
-			$query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
410
-				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
411
-			)));
412
-		}
413
-
414
-		$result = $query->execute();
415
-		$count = $result->fetchOne();
416
-		$result->closeCursor();
417
-
418
-		if ($count !== false) {
419
-			$count = (int)$count;
420
-		} else {
421
-			$count = 0;
422
-		}
423
-
424
-		return $count;
425
-	}
426
-
427
-	/**
428
-	 * get the number of disabled users in a group
429
-	 *
430
-	 * @param string $search
431
-	 *
432
-	 * @return int
433
-	 */
434
-	public function countDisabledInGroup(string $gid): int {
435
-		$this->fixDI();
436
-
437
-		$query = $this->dbConn->getQueryBuilder();
438
-		$query->select($query->createFunction('COUNT(DISTINCT ' . $query->getColumnName('uid') . ')'))
439
-			->from('preferences', 'p')
440
-			->innerJoin('p', 'group_user', 'g', $query->expr()->eq('p.userid', 'g.uid'))
441
-			->where($query->expr()->eq('appid', $query->createNamedParameter('core')))
442
-			->andWhere($query->expr()->eq('configkey', $query->createNamedParameter('enabled')))
443
-			->andWhere($query->expr()->eq('configvalue', $query->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
444
-			->andWhere($query->expr()->eq('gid', $query->createNamedParameter($gid), IQueryBuilder::PARAM_STR));
445
-
446
-		$result = $query->execute();
447
-		$count = $result->fetchOne();
448
-		$result->closeCursor();
449
-
450
-		if ($count !== false) {
451
-			$count = (int)$count;
452
-		} else {
453
-			$count = 0;
454
-		}
455
-
456
-		return $count;
457
-	}
458
-
459
-	public function getDisplayName(string $gid): string {
460
-		if (isset($this->groupCache[$gid])) {
461
-			$displayName = $this->groupCache[$gid]['displayname'];
462
-
463
-			if (isset($displayName) && trim($displayName) !== '') {
464
-				return $displayName;
465
-			}
466
-		}
467
-
468
-		$this->fixDI();
469
-
470
-		$query = $this->dbConn->getQueryBuilder();
471
-		$query->select('displayname')
472
-			->from('groups')
473
-			->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
474
-
475
-		$result = $query->execute();
476
-		$displayName = $result->fetchOne();
477
-		$result->closeCursor();
478
-
479
-		return (string) $displayName;
480
-	}
481
-
482
-	public function getGroupDetails(string $gid): array {
483
-		$displayName = $this->getDisplayName($gid);
484
-		if ($displayName !== '') {
485
-			return ['displayName' => $displayName];
486
-		}
487
-
488
-		return [];
489
-	}
490
-
491
-	public function setDisplayName(string $gid, string $displayName): bool {
492
-		if (!$this->groupExists($gid)) {
493
-			return false;
494
-		}
495
-
496
-		$this->fixDI();
497
-
498
-		$displayName = trim($displayName);
499
-		if ($displayName === '') {
500
-			$displayName = $gid;
501
-		}
502
-
503
-		$query = $this->dbConn->getQueryBuilder();
504
-		$query->update('groups')
505
-			->set('displayname', $query->createNamedParameter($displayName))
506
-			->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
507
-		$query->execute();
508
-
509
-		return true;
510
-	}
511
-
512
-	/**
513
-	 * Backend name to be shown in group management
514
-	 * @return string the name of the backend to be shown
515
-	 * @since 21.0.0
516
-	 */
517
-	public function getBackendName(): string {
518
-		return 'Database';
519
-	}
54
+    IAddToGroupBackend,
55
+    ICountDisabledInGroup,
56
+    ICountUsersBackend,
57
+    ICreateGroupBackend,
58
+    IDeleteGroupBackend,
59
+    IGetDisplayNameBackend,
60
+    IGroupDetailsBackend,
61
+    IRemoveFromGroupBackend,
62
+    ISetDisplayNameBackend,
63
+    ISearchableGroupBackend,
64
+    INamedBackend {
65
+    /** @var string[] */
66
+    private $groupCache = [];
67
+
68
+    /** @var IDBConnection */
69
+    private $dbConn;
70
+
71
+    /**
72
+     * \OC\Group\Database constructor.
73
+     *
74
+     * @param IDBConnection|null $dbConn
75
+     */
76
+    public function __construct(IDBConnection $dbConn = null) {
77
+        $this->dbConn = $dbConn;
78
+    }
79
+
80
+    /**
81
+     * FIXME: This function should not be required!
82
+     */
83
+    private function fixDI() {
84
+        if ($this->dbConn === null) {
85
+            $this->dbConn = \OC::$server->getDatabaseConnection();
86
+        }
87
+    }
88
+
89
+    /**
90
+     * Try to create a new group
91
+     * @param string $gid The name of the group to create
92
+     * @return bool
93
+     *
94
+     * Tries to create a new group. If the group name already exists, false will
95
+     * be returned.
96
+     */
97
+    public function createGroup(string $gid): bool {
98
+        $this->fixDI();
99
+
100
+        try {
101
+            // Add group
102
+            $builder = $this->dbConn->getQueryBuilder();
103
+            $result = $builder->insert('groups')
104
+                ->setValue('gid', $builder->createNamedParameter($gid))
105
+                ->setValue('displayname', $builder->createNamedParameter($gid))
106
+                ->execute();
107
+        } catch (UniqueConstraintViolationException $e) {
108
+            $result = 0;
109
+        }
110
+
111
+        // Add to cache
112
+        $this->groupCache[$gid] = [
113
+            'gid' => $gid,
114
+            'displayname' => $gid
115
+        ];
116
+
117
+        return $result === 1;
118
+    }
119
+
120
+    /**
121
+     * delete a group
122
+     * @param string $gid gid of the group to delete
123
+     * @return bool
124
+     *
125
+     * Deletes a group and removes it from the group_user-table
126
+     */
127
+    public function deleteGroup(string $gid): bool {
128
+        $this->fixDI();
129
+
130
+        // Delete the group
131
+        $qb = $this->dbConn->getQueryBuilder();
132
+        $qb->delete('groups')
133
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
134
+            ->execute();
135
+
136
+        // Delete the group-user relation
137
+        $qb = $this->dbConn->getQueryBuilder();
138
+        $qb->delete('group_user')
139
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
140
+            ->execute();
141
+
142
+        // Delete the group-groupadmin relation
143
+        $qb = $this->dbConn->getQueryBuilder();
144
+        $qb->delete('group_admin')
145
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
146
+            ->execute();
147
+
148
+        // Delete from cache
149
+        unset($this->groupCache[$gid]);
150
+
151
+        return true;
152
+    }
153
+
154
+    /**
155
+     * is user in group?
156
+     * @param string $uid uid of the user
157
+     * @param string $gid gid of the group
158
+     * @return bool
159
+     *
160
+     * Checks whether the user is member of a group or not.
161
+     */
162
+    public function inGroup($uid, $gid) {
163
+        $this->fixDI();
164
+
165
+        // check
166
+        $qb = $this->dbConn->getQueryBuilder();
167
+        $cursor = $qb->select('uid')
168
+            ->from('group_user')
169
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
170
+            ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
171
+            ->execute();
172
+
173
+        $result = $cursor->fetch();
174
+        $cursor->closeCursor();
175
+
176
+        return $result ? true : false;
177
+    }
178
+
179
+    /**
180
+     * Add a user to a group
181
+     * @param string $uid Name of the user to add to group
182
+     * @param string $gid Name of the group in which add the user
183
+     * @return bool
184
+     *
185
+     * Adds a user to a group.
186
+     */
187
+    public function addToGroup(string $uid, string $gid): bool {
188
+        $this->fixDI();
189
+
190
+        // No duplicate entries!
191
+        if (!$this->inGroup($uid, $gid)) {
192
+            $qb = $this->dbConn->getQueryBuilder();
193
+            $qb->insert('group_user')
194
+                ->setValue('uid', $qb->createNamedParameter($uid))
195
+                ->setValue('gid', $qb->createNamedParameter($gid))
196
+                ->execute();
197
+            return true;
198
+        } else {
199
+            return false;
200
+        }
201
+    }
202
+
203
+    /**
204
+     * Removes a user from a group
205
+     * @param string $uid Name of the user to remove from group
206
+     * @param string $gid Name of the group from which remove the user
207
+     * @return bool
208
+     *
209
+     * removes the user from a group.
210
+     */
211
+    public function removeFromGroup(string $uid, string $gid): bool {
212
+        $this->fixDI();
213
+
214
+        $qb = $this->dbConn->getQueryBuilder();
215
+        $qb->delete('group_user')
216
+            ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
217
+            ->andWhere($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
218
+            ->execute();
219
+
220
+        return true;
221
+    }
222
+
223
+    /**
224
+     * Get all groups a user belongs to
225
+     * @param string $uid Name of the user
226
+     * @return array an array of group names
227
+     *
228
+     * This function fetches all groups a user belongs to. It does not check
229
+     * if the user exists at all.
230
+     */
231
+    public function getUserGroups($uid) {
232
+        //guests has empty or null $uid
233
+        if ($uid === null || $uid === '') {
234
+            return [];
235
+        }
236
+
237
+        $this->fixDI();
238
+
239
+        // No magic!
240
+        $qb = $this->dbConn->getQueryBuilder();
241
+        $cursor = $qb->select('gu.gid', 'g.displayname')
242
+            ->from('group_user', 'gu')
243
+            ->leftJoin('gu', 'groups', 'g', $qb->expr()->eq('gu.gid', 'g.gid'))
244
+            ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
245
+            ->execute();
246
+
247
+        $groups = [];
248
+        while ($row = $cursor->fetch()) {
249
+            $groups[] = $row['gid'];
250
+            $this->groupCache[$row['gid']] = [
251
+                'gid' => $row['gid'],
252
+                'displayname' => $row['displayname'],
253
+            ];
254
+        }
255
+        $cursor->closeCursor();
256
+
257
+        return $groups;
258
+    }
259
+
260
+    /**
261
+     * get a list of all groups
262
+     * @param string $search
263
+     * @param int $limit
264
+     * @param int $offset
265
+     * @return array an array of group names
266
+     *
267
+     * Returns a list with all groups
268
+     */
269
+    public function getGroups(string $search = '', int $limit = -1, int $offset = 0) {
270
+        $this->fixDI();
271
+
272
+        $query = $this->dbConn->getQueryBuilder();
273
+        $query->select('gid')
274
+            ->from('groups')
275
+            ->orderBy('gid', 'ASC');
276
+
277
+        if ($search !== '') {
278
+            $query->where($query->expr()->iLike('gid', $query->createNamedParameter(
279
+                '%' . $this->dbConn->escapeLikeParameter($search) . '%'
280
+            )));
281
+            $query->orWhere($query->expr()->iLike('displayname', $query->createNamedParameter(
282
+                '%' . $this->dbConn->escapeLikeParameter($search) . '%'
283
+            )));
284
+        }
285
+
286
+        if ($limit > 0) {
287
+            $query->setMaxResults($limit);
288
+        }
289
+        if ($offset > 0) {
290
+            $query->setFirstResult($offset);
291
+        }
292
+        $result = $query->execute();
293
+
294
+        $groups = [];
295
+        while ($row = $result->fetch()) {
296
+            $groups[] = $row['gid'];
297
+        }
298
+        $result->closeCursor();
299
+
300
+        return $groups;
301
+    }
302
+
303
+    /**
304
+     * check if a group exists
305
+     * @param string $gid
306
+     * @return bool
307
+     */
308
+    public function groupExists($gid) {
309
+        $this->fixDI();
310
+
311
+        // Check cache first
312
+        if (isset($this->groupCache[$gid])) {
313
+            return true;
314
+        }
315
+
316
+        $qb = $this->dbConn->getQueryBuilder();
317
+        $cursor = $qb->select('gid', 'displayname')
318
+            ->from('groups')
319
+            ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
320
+            ->execute();
321
+        $result = $cursor->fetch();
322
+        $cursor->closeCursor();
323
+
324
+        if ($result !== false) {
325
+            $this->groupCache[$gid] = [
326
+                'gid' => $gid,
327
+                'displayname' => $result['displayname'],
328
+            ];
329
+            return true;
330
+        }
331
+        return false;
332
+    }
333
+
334
+    /**
335
+     * Get a list of all users in a group
336
+     * @param string $gid
337
+     * @param string $search
338
+     * @param int $limit
339
+     * @param int $offset
340
+     * @return array<int,string> an array of user ids
341
+     */
342
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0): array {
343
+        return array_values(array_map(fn ($user) => $user->getUid(), $this->searchInGroup($gid, $search, $limit, $offset)));
344
+    }
345
+
346
+    public function searchInGroup(string $gid, string $search = '', int $limit = -1, int $offset = 0): array {
347
+        $this->fixDI();
348
+
349
+        $query = $this->dbConn->getQueryBuilder();
350
+        $query->select('g.uid', 'u.displayname');
351
+
352
+        $query->from('group_user', 'g')
353
+            ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)))
354
+            ->orderBy('g.uid', 'ASC');
355
+
356
+        $query->leftJoin('g', 'users', 'u', $query->expr()->eq('g.uid', 'u.uid'));
357
+
358
+        if ($search !== '') {
359
+            $query->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
360
+                $query->expr()->eq('p.userid', 'u.uid'),
361
+                $query->expr()->eq('p.appid', $query->expr()->literal('settings')),
362
+                $query->expr()->eq('p.configkey', $query->expr()->literal('email'))
363
+            ))
364
+                // sqlite doesn't like re-using a single named parameter here
365
+                ->andWhere(
366
+                    $query->expr()->orX(
367
+                        $query->expr()->ilike('g.uid', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')),
368
+                        $query->expr()->ilike('u.displayname', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')),
369
+                        $query->expr()->ilike('p.configvalue', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%'))
370
+                    )
371
+                )
372
+                ->orderBy('u.uid_lower', 'ASC');
373
+        }
374
+
375
+        if ($limit !== -1) {
376
+            $query->setMaxResults($limit);
377
+        }
378
+        if ($offset !== 0) {
379
+            $query->setFirstResult($offset);
380
+        }
381
+
382
+        $result = $query->executeQuery();
383
+
384
+        $users = [];
385
+        $userManager = \OCP\Server::get(IUserManager::class);
386
+        while ($row = $result->fetch()) {
387
+            $users[$row['uid']] = new LazyUser($row['uid'], $userManager, $row['displayname'] ?? null);
388
+        }
389
+        $result->closeCursor();
390
+
391
+        return $users;
392
+    }
393
+
394
+    /**
395
+     * get the number of all users matching the search string in a group
396
+     * @param string $gid
397
+     * @param string $search
398
+     * @return int
399
+     */
400
+    public function countUsersInGroup(string $gid, string $search = ''): int {
401
+        $this->fixDI();
402
+
403
+        $query = $this->dbConn->getQueryBuilder();
404
+        $query->select($query->func()->count('*', 'num_users'))
405
+            ->from('group_user')
406
+            ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
407
+
408
+        if ($search !== '') {
409
+            $query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
410
+                '%' . $this->dbConn->escapeLikeParameter($search) . '%'
411
+            )));
412
+        }
413
+
414
+        $result = $query->execute();
415
+        $count = $result->fetchOne();
416
+        $result->closeCursor();
417
+
418
+        if ($count !== false) {
419
+            $count = (int)$count;
420
+        } else {
421
+            $count = 0;
422
+        }
423
+
424
+        return $count;
425
+    }
426
+
427
+    /**
428
+     * get the number of disabled users in a group
429
+     *
430
+     * @param string $search
431
+     *
432
+     * @return int
433
+     */
434
+    public function countDisabledInGroup(string $gid): int {
435
+        $this->fixDI();
436
+
437
+        $query = $this->dbConn->getQueryBuilder();
438
+        $query->select($query->createFunction('COUNT(DISTINCT ' . $query->getColumnName('uid') . ')'))
439
+            ->from('preferences', 'p')
440
+            ->innerJoin('p', 'group_user', 'g', $query->expr()->eq('p.userid', 'g.uid'))
441
+            ->where($query->expr()->eq('appid', $query->createNamedParameter('core')))
442
+            ->andWhere($query->expr()->eq('configkey', $query->createNamedParameter('enabled')))
443
+            ->andWhere($query->expr()->eq('configvalue', $query->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
444
+            ->andWhere($query->expr()->eq('gid', $query->createNamedParameter($gid), IQueryBuilder::PARAM_STR));
445
+
446
+        $result = $query->execute();
447
+        $count = $result->fetchOne();
448
+        $result->closeCursor();
449
+
450
+        if ($count !== false) {
451
+            $count = (int)$count;
452
+        } else {
453
+            $count = 0;
454
+        }
455
+
456
+        return $count;
457
+    }
458
+
459
+    public function getDisplayName(string $gid): string {
460
+        if (isset($this->groupCache[$gid])) {
461
+            $displayName = $this->groupCache[$gid]['displayname'];
462
+
463
+            if (isset($displayName) && trim($displayName) !== '') {
464
+                return $displayName;
465
+            }
466
+        }
467
+
468
+        $this->fixDI();
469
+
470
+        $query = $this->dbConn->getQueryBuilder();
471
+        $query->select('displayname')
472
+            ->from('groups')
473
+            ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
474
+
475
+        $result = $query->execute();
476
+        $displayName = $result->fetchOne();
477
+        $result->closeCursor();
478
+
479
+        return (string) $displayName;
480
+    }
481
+
482
+    public function getGroupDetails(string $gid): array {
483
+        $displayName = $this->getDisplayName($gid);
484
+        if ($displayName !== '') {
485
+            return ['displayName' => $displayName];
486
+        }
487
+
488
+        return [];
489
+    }
490
+
491
+    public function setDisplayName(string $gid, string $displayName): bool {
492
+        if (!$this->groupExists($gid)) {
493
+            return false;
494
+        }
495
+
496
+        $this->fixDI();
497
+
498
+        $displayName = trim($displayName);
499
+        if ($displayName === '') {
500
+            $displayName = $gid;
501
+        }
502
+
503
+        $query = $this->dbConn->getQueryBuilder();
504
+        $query->update('groups')
505
+            ->set('displayname', $query->createNamedParameter($displayName))
506
+            ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
507
+        $query->execute();
508
+
509
+        return true;
510
+    }
511
+
512
+    /**
513
+     * Backend name to be shown in group management
514
+     * @return string the name of the backend to be shown
515
+     * @since 21.0.0
516
+     */
517
+    public function getBackendName(): string {
518
+        return 'Database';
519
+    }
520 520
 }
Please login to merge, or discard this patch.
lib/private/Group/Manager.php 1 patch
Indentation   +365 added lines, -365 removed lines patch added patch discarded remove patch
@@ -65,369 +65,369 @@
 block discarded – undo
65 65
  * @package OC\Group
66 66
  */
67 67
 class Manager extends PublicEmitter implements IGroupManager {
68
-	/** @var GroupInterface[] */
69
-	private $backends = [];
70
-
71
-	/** @var \OC\User\Manager */
72
-	private $userManager;
73
-	/** @var EventDispatcherInterface */
74
-	private $dispatcher;
75
-	private LoggerInterface $logger;
76
-
77
-	/** @var \OC\Group\Group[] */
78
-	private $cachedGroups = [];
79
-
80
-	/** @var (string[])[] */
81
-	private $cachedUserGroups = [];
82
-
83
-	/** @var \OC\SubAdmin */
84
-	private $subAdmin = null;
85
-
86
-	private DisplayNameCache $displayNameCache;
87
-
88
-	public function __construct(\OC\User\Manager $userManager,
89
-								EventDispatcherInterface $dispatcher,
90
-								LoggerInterface $logger,
91
-								ICacheFactory $cacheFactory) {
92
-		$this->userManager = $userManager;
93
-		$this->dispatcher = $dispatcher;
94
-		$this->logger = $logger;
95
-		$this->displayNameCache = new DisplayNameCache($cacheFactory, $this);
96
-
97
-		$cachedGroups = &$this->cachedGroups;
98
-		$cachedUserGroups = &$this->cachedUserGroups;
99
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
100
-			/**
101
-			 * @var \OC\Group\Group $group
102
-			 */
103
-			unset($cachedGroups[$group->getGID()]);
104
-			$cachedUserGroups = [];
105
-		});
106
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
107
-			/**
108
-			 * @var \OC\Group\Group $group
109
-			 */
110
-			$cachedUserGroups = [];
111
-		});
112
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
113
-			/**
114
-			 * @var \OC\Group\Group $group
115
-			 */
116
-			$cachedUserGroups = [];
117
-		});
118
-	}
119
-
120
-	/**
121
-	 * Checks whether a given backend is used
122
-	 *
123
-	 * @param string $backendClass Full classname including complete namespace
124
-	 * @return bool
125
-	 */
126
-	public function isBackendUsed($backendClass) {
127
-		$backendClass = strtolower(ltrim($backendClass, '\\'));
128
-
129
-		foreach ($this->backends as $backend) {
130
-			if (strtolower(get_class($backend)) === $backendClass) {
131
-				return true;
132
-			}
133
-		}
134
-
135
-		return false;
136
-	}
137
-
138
-	/**
139
-	 * @param \OCP\GroupInterface $backend
140
-	 */
141
-	public function addBackend($backend) {
142
-		$this->backends[] = $backend;
143
-		$this->clearCaches();
144
-	}
145
-
146
-	public function clearBackends() {
147
-		$this->backends = [];
148
-		$this->clearCaches();
149
-	}
150
-
151
-	/**
152
-	 * Get the active backends
153
-	 *
154
-	 * @return \OCP\GroupInterface[]
155
-	 */
156
-	public function getBackends() {
157
-		return $this->backends;
158
-	}
159
-
160
-
161
-	protected function clearCaches() {
162
-		$this->cachedGroups = [];
163
-		$this->cachedUserGroups = [];
164
-	}
165
-
166
-	/**
167
-	 * @param string $gid
168
-	 * @return IGroup|null
169
-	 */
170
-	public function get($gid) {
171
-		if (isset($this->cachedGroups[$gid])) {
172
-			return $this->cachedGroups[$gid];
173
-		}
174
-		return $this->getGroupObject($gid);
175
-	}
176
-
177
-	/**
178
-	 * @param string $gid
179
-	 * @param string $displayName
180
-	 * @return \OCP\IGroup|null
181
-	 */
182
-	protected function getGroupObject($gid, $displayName = null) {
183
-		$backends = [];
184
-		foreach ($this->backends as $backend) {
185
-			if ($backend->implementsActions(Backend::GROUP_DETAILS)) {
186
-				$groupData = $backend->getGroupDetails($gid);
187
-				if (is_array($groupData) && !empty($groupData)) {
188
-					// take the display name from the first backend that has a non-null one
189
-					if (is_null($displayName) && isset($groupData['displayName'])) {
190
-						$displayName = $groupData['displayName'];
191
-					}
192
-					$backends[] = $backend;
193
-				}
194
-			} elseif ($backend->groupExists($gid)) {
195
-				$backends[] = $backend;
196
-			}
197
-		}
198
-		if (count($backends) === 0) {
199
-			return null;
200
-		}
201
-		$this->cachedGroups[$gid] = new Group($gid, $backends, $this->dispatcher, $this->userManager, $this, $displayName);
202
-		return $this->cachedGroups[$gid];
203
-	}
204
-
205
-	/**
206
-	 * @param string $gid
207
-	 * @return bool
208
-	 */
209
-	public function groupExists($gid) {
210
-		return $this->get($gid) instanceof IGroup;
211
-	}
212
-
213
-	/**
214
-	 * @param string $gid
215
-	 * @return IGroup|null
216
-	 */
217
-	public function createGroup($gid) {
218
-		if ($gid === '' || $gid === null) {
219
-			return null;
220
-		} elseif ($group = $this->get($gid)) {
221
-			return $group;
222
-		} else {
223
-			$this->emit('\OC\Group', 'preCreate', [$gid]);
224
-			foreach ($this->backends as $backend) {
225
-				if ($backend->implementsActions(Backend::CREATE_GROUP)) {
226
-					if ($backend->createGroup($gid)) {
227
-						$group = $this->getGroupObject($gid);
228
-						$this->emit('\OC\Group', 'postCreate', [$group]);
229
-						return $group;
230
-					}
231
-				}
232
-			}
233
-			return null;
234
-		}
235
-	}
236
-
237
-	/**
238
-	 * @param string $search
239
-	 * @param ?int $limit
240
-	 * @param ?int $offset
241
-	 * @return \OC\Group\Group[]
242
-	 */
243
-	public function search(string $search, ?int $limit = null, ?int $offset = 0) {
244
-		$groups = [];
245
-		foreach ($this->backends as $backend) {
246
-			$groupIds = $backend->getGroups($search, $limit ?? -1, $offset ?? 0);
247
-			foreach ($groupIds as $groupId) {
248
-				$aGroup = $this->get($groupId);
249
-				if ($aGroup instanceof IGroup) {
250
-					$groups[$groupId] = $aGroup;
251
-				} else {
252
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
253
-				}
254
-			}
255
-			if (!is_null($limit) and $limit <= 0) {
256
-				return array_values($groups);
257
-			}
258
-		}
259
-		return array_values($groups);
260
-	}
261
-
262
-	/**
263
-	 * @param IUser|null $user
264
-	 * @return \OC\Group\Group[]
265
-	 */
266
-	public function getUserGroups(IUser $user = null) {
267
-		if (!$user instanceof IUser) {
268
-			return [];
269
-		}
270
-		return $this->getUserIdGroups($user->getUID());
271
-	}
272
-
273
-	/**
274
-	 * @param string $uid the user id
275
-	 * @return \OC\Group\Group[]
276
-	 */
277
-	public function getUserIdGroups(string $uid): array {
278
-		$groups = [];
279
-
280
-		foreach ($this->getUserIdGroupIds($uid) as $groupId) {
281
-			$aGroup = $this->get($groupId);
282
-			if ($aGroup instanceof IGroup) {
283
-				$groups[$groupId] = $aGroup;
284
-			} else {
285
-				$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
286
-			}
287
-		}
288
-
289
-		return $groups;
290
-	}
291
-
292
-	/**
293
-	 * Checks if a userId is in the admin group
294
-	 *
295
-	 * @param string $userId
296
-	 * @return bool if admin
297
-	 */
298
-	public function isAdmin($userId) {
299
-		foreach ($this->backends as $backend) {
300
-			if ($backend->implementsActions(Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
301
-				return true;
302
-			}
303
-		}
304
-		return $this->isInGroup($userId, 'admin');
305
-	}
306
-
307
-	/**
308
-	 * Checks if a userId is in a group
309
-	 *
310
-	 * @param string $userId
311
-	 * @param string $group
312
-	 * @return bool if in group
313
-	 */
314
-	public function isInGroup($userId, $group) {
315
-		return array_search($group, $this->getUserIdGroupIds($userId)) !== false;
316
-	}
317
-
318
-	/**
319
-	 * get a list of group ids for a user
320
-	 *
321
-	 * @param IUser $user
322
-	 * @return string[] with group ids
323
-	 */
324
-	public function getUserGroupIds(IUser $user): array {
325
-		return $this->getUserIdGroupIds($user->getUID());
326
-	}
327
-
328
-	/**
329
-	 * @param string $uid the user id
330
-	 * @return string[]
331
-	 */
332
-	private function getUserIdGroupIds(string $uid): array {
333
-		if (!isset($this->cachedUserGroups[$uid])) {
334
-			$groups = [];
335
-			foreach ($this->backends as $backend) {
336
-				if ($groupIds = $backend->getUserGroups($uid)) {
337
-					$groups = array_merge($groups, $groupIds);
338
-				}
339
-			}
340
-			$this->cachedUserGroups[$uid] = $groups;
341
-		}
342
-
343
-		return $this->cachedUserGroups[$uid];
344
-	}
345
-
346
-	/**
347
-	 * @param string $groupId
348
-	 * @return ?string
349
-	 */
350
-	public function getDisplayName(string $groupId): ?string {
351
-		return $this->displayNameCache->getDisplayName($groupId);
352
-	}
353
-
354
-	/**
355
-	 * get an array of groupid and displayName for a user
356
-	 *
357
-	 * @param IUser $user
358
-	 * @return array ['displayName' => displayname]
359
-	 */
360
-	public function getUserGroupNames(IUser $user) {
361
-		return array_map(function ($group) {
362
-			return ['displayName' => $this->displayNameCache->getDisplayName($group->getGID())];
363
-		}, $this->getUserGroups($user));
364
-	}
365
-
366
-	/**
367
-	 * get a list of all display names in a group
368
-	 *
369
-	 * @param string $gid
370
-	 * @param string $search
371
-	 * @param int $limit
372
-	 * @param int $offset
373
-	 * @return array an array of display names (value) and user ids (key)
374
-	 */
375
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
376
-		$group = $this->get($gid);
377
-		if (is_null($group)) {
378
-			return [];
379
-		}
380
-
381
-		$search = trim($search);
382
-		$groupUsers = [];
383
-
384
-		if (!empty($search)) {
385
-			// only user backends have the capability to do a complex search for users
386
-			$searchOffset = 0;
387
-			$searchLimit = $limit * 100;
388
-			if ($limit === -1) {
389
-				$searchLimit = 500;
390
-			}
391
-
392
-			do {
393
-				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
394
-				foreach ($filteredUsers as $filteredUser) {
395
-					if ($group->inGroup($filteredUser)) {
396
-						$groupUsers[] = $filteredUser;
397
-					}
398
-				}
399
-				$searchOffset += $searchLimit;
400
-			} while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
401
-
402
-			if ($limit === -1) {
403
-				$groupUsers = array_slice($groupUsers, $offset);
404
-			} else {
405
-				$groupUsers = array_slice($groupUsers, $offset, $limit);
406
-			}
407
-		} else {
408
-			$groupUsers = $group->searchUsers('', $limit, $offset);
409
-		}
410
-
411
-		$matchingUsers = [];
412
-		foreach ($groupUsers as $groupUser) {
413
-			$matchingUsers[(string) $groupUser->getUID()] = $groupUser->getDisplayName();
414
-		}
415
-		return $matchingUsers;
416
-	}
417
-
418
-	/**
419
-	 * @return \OC\SubAdmin
420
-	 */
421
-	public function getSubAdmin() {
422
-		if (!$this->subAdmin) {
423
-			$this->subAdmin = new \OC\SubAdmin(
424
-				$this->userManager,
425
-				$this,
426
-				\OC::$server->getDatabaseConnection(),
427
-				\OC::$server->get(IEventDispatcher::class)
428
-			);
429
-		}
430
-
431
-		return $this->subAdmin;
432
-	}
68
+    /** @var GroupInterface[] */
69
+    private $backends = [];
70
+
71
+    /** @var \OC\User\Manager */
72
+    private $userManager;
73
+    /** @var EventDispatcherInterface */
74
+    private $dispatcher;
75
+    private LoggerInterface $logger;
76
+
77
+    /** @var \OC\Group\Group[] */
78
+    private $cachedGroups = [];
79
+
80
+    /** @var (string[])[] */
81
+    private $cachedUserGroups = [];
82
+
83
+    /** @var \OC\SubAdmin */
84
+    private $subAdmin = null;
85
+
86
+    private DisplayNameCache $displayNameCache;
87
+
88
+    public function __construct(\OC\User\Manager $userManager,
89
+                                EventDispatcherInterface $dispatcher,
90
+                                LoggerInterface $logger,
91
+                                ICacheFactory $cacheFactory) {
92
+        $this->userManager = $userManager;
93
+        $this->dispatcher = $dispatcher;
94
+        $this->logger = $logger;
95
+        $this->displayNameCache = new DisplayNameCache($cacheFactory, $this);
96
+
97
+        $cachedGroups = &$this->cachedGroups;
98
+        $cachedUserGroups = &$this->cachedUserGroups;
99
+        $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
100
+            /**
101
+             * @var \OC\Group\Group $group
102
+             */
103
+            unset($cachedGroups[$group->getGID()]);
104
+            $cachedUserGroups = [];
105
+        });
106
+        $this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
107
+            /**
108
+             * @var \OC\Group\Group $group
109
+             */
110
+            $cachedUserGroups = [];
111
+        });
112
+        $this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
113
+            /**
114
+             * @var \OC\Group\Group $group
115
+             */
116
+            $cachedUserGroups = [];
117
+        });
118
+    }
119
+
120
+    /**
121
+     * Checks whether a given backend is used
122
+     *
123
+     * @param string $backendClass Full classname including complete namespace
124
+     * @return bool
125
+     */
126
+    public function isBackendUsed($backendClass) {
127
+        $backendClass = strtolower(ltrim($backendClass, '\\'));
128
+
129
+        foreach ($this->backends as $backend) {
130
+            if (strtolower(get_class($backend)) === $backendClass) {
131
+                return true;
132
+            }
133
+        }
134
+
135
+        return false;
136
+    }
137
+
138
+    /**
139
+     * @param \OCP\GroupInterface $backend
140
+     */
141
+    public function addBackend($backend) {
142
+        $this->backends[] = $backend;
143
+        $this->clearCaches();
144
+    }
145
+
146
+    public function clearBackends() {
147
+        $this->backends = [];
148
+        $this->clearCaches();
149
+    }
150
+
151
+    /**
152
+     * Get the active backends
153
+     *
154
+     * @return \OCP\GroupInterface[]
155
+     */
156
+    public function getBackends() {
157
+        return $this->backends;
158
+    }
159
+
160
+
161
+    protected function clearCaches() {
162
+        $this->cachedGroups = [];
163
+        $this->cachedUserGroups = [];
164
+    }
165
+
166
+    /**
167
+     * @param string $gid
168
+     * @return IGroup|null
169
+     */
170
+    public function get($gid) {
171
+        if (isset($this->cachedGroups[$gid])) {
172
+            return $this->cachedGroups[$gid];
173
+        }
174
+        return $this->getGroupObject($gid);
175
+    }
176
+
177
+    /**
178
+     * @param string $gid
179
+     * @param string $displayName
180
+     * @return \OCP\IGroup|null
181
+     */
182
+    protected function getGroupObject($gid, $displayName = null) {
183
+        $backends = [];
184
+        foreach ($this->backends as $backend) {
185
+            if ($backend->implementsActions(Backend::GROUP_DETAILS)) {
186
+                $groupData = $backend->getGroupDetails($gid);
187
+                if (is_array($groupData) && !empty($groupData)) {
188
+                    // take the display name from the first backend that has a non-null one
189
+                    if (is_null($displayName) && isset($groupData['displayName'])) {
190
+                        $displayName = $groupData['displayName'];
191
+                    }
192
+                    $backends[] = $backend;
193
+                }
194
+            } elseif ($backend->groupExists($gid)) {
195
+                $backends[] = $backend;
196
+            }
197
+        }
198
+        if (count($backends) === 0) {
199
+            return null;
200
+        }
201
+        $this->cachedGroups[$gid] = new Group($gid, $backends, $this->dispatcher, $this->userManager, $this, $displayName);
202
+        return $this->cachedGroups[$gid];
203
+    }
204
+
205
+    /**
206
+     * @param string $gid
207
+     * @return bool
208
+     */
209
+    public function groupExists($gid) {
210
+        return $this->get($gid) instanceof IGroup;
211
+    }
212
+
213
+    /**
214
+     * @param string $gid
215
+     * @return IGroup|null
216
+     */
217
+    public function createGroup($gid) {
218
+        if ($gid === '' || $gid === null) {
219
+            return null;
220
+        } elseif ($group = $this->get($gid)) {
221
+            return $group;
222
+        } else {
223
+            $this->emit('\OC\Group', 'preCreate', [$gid]);
224
+            foreach ($this->backends as $backend) {
225
+                if ($backend->implementsActions(Backend::CREATE_GROUP)) {
226
+                    if ($backend->createGroup($gid)) {
227
+                        $group = $this->getGroupObject($gid);
228
+                        $this->emit('\OC\Group', 'postCreate', [$group]);
229
+                        return $group;
230
+                    }
231
+                }
232
+            }
233
+            return null;
234
+        }
235
+    }
236
+
237
+    /**
238
+     * @param string $search
239
+     * @param ?int $limit
240
+     * @param ?int $offset
241
+     * @return \OC\Group\Group[]
242
+     */
243
+    public function search(string $search, ?int $limit = null, ?int $offset = 0) {
244
+        $groups = [];
245
+        foreach ($this->backends as $backend) {
246
+            $groupIds = $backend->getGroups($search, $limit ?? -1, $offset ?? 0);
247
+            foreach ($groupIds as $groupId) {
248
+                $aGroup = $this->get($groupId);
249
+                if ($aGroup instanceof IGroup) {
250
+                    $groups[$groupId] = $aGroup;
251
+                } else {
252
+                    $this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
253
+                }
254
+            }
255
+            if (!is_null($limit) and $limit <= 0) {
256
+                return array_values($groups);
257
+            }
258
+        }
259
+        return array_values($groups);
260
+    }
261
+
262
+    /**
263
+     * @param IUser|null $user
264
+     * @return \OC\Group\Group[]
265
+     */
266
+    public function getUserGroups(IUser $user = null) {
267
+        if (!$user instanceof IUser) {
268
+            return [];
269
+        }
270
+        return $this->getUserIdGroups($user->getUID());
271
+    }
272
+
273
+    /**
274
+     * @param string $uid the user id
275
+     * @return \OC\Group\Group[]
276
+     */
277
+    public function getUserIdGroups(string $uid): array {
278
+        $groups = [];
279
+
280
+        foreach ($this->getUserIdGroupIds($uid) as $groupId) {
281
+            $aGroup = $this->get($groupId);
282
+            if ($aGroup instanceof IGroup) {
283
+                $groups[$groupId] = $aGroup;
284
+            } else {
285
+                $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
286
+            }
287
+        }
288
+
289
+        return $groups;
290
+    }
291
+
292
+    /**
293
+     * Checks if a userId is in the admin group
294
+     *
295
+     * @param string $userId
296
+     * @return bool if admin
297
+     */
298
+    public function isAdmin($userId) {
299
+        foreach ($this->backends as $backend) {
300
+            if ($backend->implementsActions(Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
301
+                return true;
302
+            }
303
+        }
304
+        return $this->isInGroup($userId, 'admin');
305
+    }
306
+
307
+    /**
308
+     * Checks if a userId is in a group
309
+     *
310
+     * @param string $userId
311
+     * @param string $group
312
+     * @return bool if in group
313
+     */
314
+    public function isInGroup($userId, $group) {
315
+        return array_search($group, $this->getUserIdGroupIds($userId)) !== false;
316
+    }
317
+
318
+    /**
319
+     * get a list of group ids for a user
320
+     *
321
+     * @param IUser $user
322
+     * @return string[] with group ids
323
+     */
324
+    public function getUserGroupIds(IUser $user): array {
325
+        return $this->getUserIdGroupIds($user->getUID());
326
+    }
327
+
328
+    /**
329
+     * @param string $uid the user id
330
+     * @return string[]
331
+     */
332
+    private function getUserIdGroupIds(string $uid): array {
333
+        if (!isset($this->cachedUserGroups[$uid])) {
334
+            $groups = [];
335
+            foreach ($this->backends as $backend) {
336
+                if ($groupIds = $backend->getUserGroups($uid)) {
337
+                    $groups = array_merge($groups, $groupIds);
338
+                }
339
+            }
340
+            $this->cachedUserGroups[$uid] = $groups;
341
+        }
342
+
343
+        return $this->cachedUserGroups[$uid];
344
+    }
345
+
346
+    /**
347
+     * @param string $groupId
348
+     * @return ?string
349
+     */
350
+    public function getDisplayName(string $groupId): ?string {
351
+        return $this->displayNameCache->getDisplayName($groupId);
352
+    }
353
+
354
+    /**
355
+     * get an array of groupid and displayName for a user
356
+     *
357
+     * @param IUser $user
358
+     * @return array ['displayName' => displayname]
359
+     */
360
+    public function getUserGroupNames(IUser $user) {
361
+        return array_map(function ($group) {
362
+            return ['displayName' => $this->displayNameCache->getDisplayName($group->getGID())];
363
+        }, $this->getUserGroups($user));
364
+    }
365
+
366
+    /**
367
+     * get a list of all display names in a group
368
+     *
369
+     * @param string $gid
370
+     * @param string $search
371
+     * @param int $limit
372
+     * @param int $offset
373
+     * @return array an array of display names (value) and user ids (key)
374
+     */
375
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
376
+        $group = $this->get($gid);
377
+        if (is_null($group)) {
378
+            return [];
379
+        }
380
+
381
+        $search = trim($search);
382
+        $groupUsers = [];
383
+
384
+        if (!empty($search)) {
385
+            // only user backends have the capability to do a complex search for users
386
+            $searchOffset = 0;
387
+            $searchLimit = $limit * 100;
388
+            if ($limit === -1) {
389
+                $searchLimit = 500;
390
+            }
391
+
392
+            do {
393
+                $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
394
+                foreach ($filteredUsers as $filteredUser) {
395
+                    if ($group->inGroup($filteredUser)) {
396
+                        $groupUsers[] = $filteredUser;
397
+                    }
398
+                }
399
+                $searchOffset += $searchLimit;
400
+            } while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
401
+
402
+            if ($limit === -1) {
403
+                $groupUsers = array_slice($groupUsers, $offset);
404
+            } else {
405
+                $groupUsers = array_slice($groupUsers, $offset, $limit);
406
+            }
407
+        } else {
408
+            $groupUsers = $group->searchUsers('', $limit, $offset);
409
+        }
410
+
411
+        $matchingUsers = [];
412
+        foreach ($groupUsers as $groupUser) {
413
+            $matchingUsers[(string) $groupUser->getUID()] = $groupUser->getDisplayName();
414
+        }
415
+        return $matchingUsers;
416
+    }
417
+
418
+    /**
419
+     * @return \OC\SubAdmin
420
+     */
421
+    public function getSubAdmin() {
422
+        if (!$this->subAdmin) {
423
+            $this->subAdmin = new \OC\SubAdmin(
424
+                $this->userManager,
425
+                $this,
426
+                \OC::$server->getDatabaseConnection(),
427
+                \OC::$server->get(IEventDispatcher::class)
428
+            );
429
+        }
430
+
431
+        return $this->subAdmin;
432
+    }
433 433
 }
Please login to merge, or discard this patch.