Passed
Push — master ( e6ef09...54cffe )
by Roeland
49:25 queued 37:20
created

Database::setDisplayName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 12
nc 3
nop 2
dl 0
loc 19
rs 9.8666
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Christoph Wurst <[email protected]>
6
 * @author Joas Schilling <[email protected]>
7
 * @author John Molakvoæ (skjnldsv) <[email protected]>
8
 * @author Loki3000 <[email protected]>
9
 * @author Morris Jobke <[email protected]>
10
 * @author Roeland Jago Douma <[email protected]>
11
 *
12
 * @license AGPL-3.0
13
 *
14
 * This code is free software: you can redistribute it and/or modify
15
 * it under the terms of the GNU Affero General Public License, version 3,
16
 * as published by the Free Software Foundation.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21
 * GNU Affero General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU Affero General Public License, version 3,
24
 * along with this program. If not, see <http://www.gnu.org/licenses/>
25
 *
26
 */
27
/*
28
 *
29
 * The following SQL statement is just a help for developers and will not be
30
 * executed!
31
 *
32
 * CREATE TABLE `groups` (
33
 *   `gid` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
34
 *   PRIMARY KEY (`gid`)
35
 * ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
36
 *
37
 * CREATE TABLE `group_user` (
38
 *   `gid` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
39
 *   `uid` varchar(64) COLLATE utf8_unicode_ci NOT NULL
40
 * ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
41
 *
42
 */
43
44
namespace OC\Group;
45
46
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
47
use OCP\DB\QueryBuilder\IQueryBuilder;
48
use OCP\Group\Backend\ABackend;
49
use OCP\Group\Backend\IAddToGroupBackend;
50
use OCP\Group\Backend\ICountDisabledInGroup;
51
use OCP\Group\Backend\ICountUsersBackend;
52
use OCP\Group\Backend\ICreateGroupBackend;
53
use OCP\Group\Backend\IDeleteGroupBackend;
54
use OCP\Group\Backend\IGetDisplayNameBackend;
55
use OCP\Group\Backend\IGroupDetailsBackend;
56
use OCP\Group\Backend\IRemoveFromGroupBackend;
57
use OCP\Group\Backend\ISetDisplayNameBackend;
58
use OCP\Group\Backend\INamedBackend;
59
use OCP\IDBConnection;
60
61
/**
62
 * Class for group management in a SQL Database (e.g. MySQL, SQLite)
63
 */
64
class Database extends ABackend implements
65
	IAddToGroupBackend,
66
			   ICountDisabledInGroup,
67
			   ICountUsersBackend,
68
			   ICreateGroupBackend,
69
			   IDeleteGroupBackend,
70
			   IGetDisplayNameBackend,
71
			   IGroupDetailsBackend,
72
			   IRemoveFromGroupBackend,
73
			   ISetDisplayNameBackend,
74
			   INamedBackend {
75
76
	/** @var string[] */
77
	private $groupCache = [];
78
79
	/** @var IDBConnection */
80
	private $dbConn;
81
82
	/**
83
	 * \OC\Group\Database constructor.
84
	 *
85
	 * @param IDBConnection|null $dbConn
86
	 */
87
	public function __construct(IDBConnection $dbConn = null) {
88
		$this->dbConn = $dbConn;
89
	}
90
91
	/**
92
	 * FIXME: This function should not be required!
93
	 */
94
	private function fixDI() {
95
		if ($this->dbConn === null) {
96
			$this->dbConn = \OC::$server->getDatabaseConnection();
97
		}
98
	}
99
100
	/**
101
	 * Try to create a new group
102
	 * @param string $gid The name of the group to create
103
	 * @return bool
104
	 *
105
	 * Tries to create a new group. If the group name already exists, false will
106
	 * be returned.
107
	 */
108
	public function createGroup(string $gid): bool {
109
		$this->fixDI();
110
111
		try {
112
			// Add group
113
			$builder = $this->dbConn->getQueryBuilder();
114
			$result = $builder->insert('groups')
115
				->setValue('gid', $builder->createNamedParameter($gid))
116
				->setValue('displayname', $builder->createNamedParameter($gid))
117
				->execute();
118
		} catch (UniqueConstraintViolationException $e) {
119
			$result = 0;
120
		}
121
122
		// Add to cache
123
		$this->groupCache[$gid] = [
124
			'gid' => $gid,
125
			'displayname' => $gid
126
		];
127
128
		return $result === 1;
129
	}
130
131
	/**
132
	 * delete a group
133
	 * @param string $gid gid of the group to delete
134
	 * @return bool
135
	 *
136
	 * Deletes a group and removes it from the group_user-table
137
	 */
138
	public function deleteGroup(string $gid): bool {
139
		$this->fixDI();
140
141
		// Delete the group
142
		$qb = $this->dbConn->getQueryBuilder();
143
		$qb->delete('groups')
144
			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
145
			->execute();
146
147
		// Delete the group-user relation
148
		$qb = $this->dbConn->getQueryBuilder();
149
		$qb->delete('group_user')
150
			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
151
			->execute();
152
153
		// Delete the group-groupadmin relation
154
		$qb = $this->dbConn->getQueryBuilder();
155
		$qb->delete('group_admin')
156
			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
157
			->execute();
158
159
		// Delete from cache
160
		unset($this->groupCache[$gid]);
161
162
		return true;
163
	}
164
165
	/**
166
	 * is user in group?
167
	 * @param string $uid uid of the user
168
	 * @param string $gid gid of the group
169
	 * @return bool
170
	 *
171
	 * Checks whether the user is member of a group or not.
172
	 */
173
	public function inGroup($uid, $gid) {
174
		$this->fixDI();
175
176
		// check
177
		$qb = $this->dbConn->getQueryBuilder();
178
		$cursor = $qb->select('uid')
179
			->from('group_user')
180
			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
181
			->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
182
			->execute();
183
184
		$result = $cursor->fetch();
185
		$cursor->closeCursor();
186
187
		return $result ? true : false;
188
	}
189
190
	/**
191
	 * Add a user to a group
192
	 * @param string $uid Name of the user to add to group
193
	 * @param string $gid Name of the group in which add the user
194
	 * @return bool
195
	 *
196
	 * Adds a user to a group.
197
	 */
198
	public function addToGroup(string $uid, string $gid): bool {
199
		$this->fixDI();
200
201
		// No duplicate entries!
202
		if (!$this->inGroup($uid, $gid)) {
203
			$qb = $this->dbConn->getQueryBuilder();
204
			$qb->insert('group_user')
205
				->setValue('uid', $qb->createNamedParameter($uid))
206
				->setValue('gid', $qb->createNamedParameter($gid))
207
				->execute();
208
			return true;
209
		} else {
210
			return false;
211
		}
212
	}
213
214
	/**
215
	 * Removes a user from a group
216
	 * @param string $uid Name of the user to remove from group
217
	 * @param string $gid Name of the group from which remove the user
218
	 * @return bool
219
	 *
220
	 * removes the user from a group.
221
	 */
222
	public function removeFromGroup(string $uid, string $gid): bool {
223
		$this->fixDI();
224
225
		$qb = $this->dbConn->getQueryBuilder();
226
		$qb->delete('group_user')
227
			->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
228
			->andWhere($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
229
			->execute();
230
231
		return true;
232
	}
233
234
	/**
235
	 * Get all groups a user belongs to
236
	 * @param string $uid Name of the user
237
	 * @return array an array of group names
238
	 *
239
	 * This function fetches all groups a user belongs to. It does not check
240
	 * if the user exists at all.
241
	 */
242
	public function getUserGroups($uid) {
243
		//guests has empty or null $uid
244
		if ($uid === null || $uid === '') {
245
			return [];
246
		}
247
248
		$this->fixDI();
249
250
		// No magic!
251
		$qb = $this->dbConn->getQueryBuilder();
252
		$cursor = $qb->select('gu.gid', 'g.displayname')
253
			->from('group_user', 'gu')
254
			->leftJoin('gu', 'groups', 'g', $qb->expr()->eq('gu.gid', 'g.gid'))
255
			->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
256
			->execute();
257
258
		$groups = [];
259
		while ($row = $cursor->fetch()) {
260
			$groups[] = $row['gid'];
261
			$this->groupCache[$row['gid']] = [
262
				'gid' => $row['gid'],
263
				'displayname' => $row['displayname'],
264
			];
265
		}
266
		$cursor->closeCursor();
267
268
		return $groups;
269
	}
270
271
	/**
272
	 * get a list of all groups
273
	 * @param string $search
274
	 * @param int $limit
275
	 * @param int $offset
276
	 * @return array an array of group names
277
	 *
278
	 * Returns a list with all groups
279
	 */
280
	public function getGroups($search = '', $limit = null, $offset = null) {
281
		$this->fixDI();
282
283
		$query = $this->dbConn->getQueryBuilder();
284
		$query->select('gid')
285
			->from('groups')
286
			->orderBy('gid', 'ASC');
287
288
		if ($search !== '') {
289
			$query->where($query->expr()->iLike('gid', $query->createNamedParameter(
290
				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
291
			)));
292
			$query->orWhere($query->expr()->iLike('displayname', $query->createNamedParameter(
293
				'%' . $this->dbConn->escapeLikeParameter($search) . '%'
294
			)));
295
		}
296
297
		$query->setMaxResults($limit)
298
			->setFirstResult($offset);
299
		$result = $query->execute();
300
301
		$groups = [];
302
		while ($row = $result->fetch()) {
303
			$groups[] = $row['gid'];
304
		}
305
		$result->closeCursor();
306
307
		return $groups;
308
	}
309
310
	/**
311
	 * check if a group exists
312
	 * @param string $gid
313
	 * @return bool
314
	 */
315
	public function groupExists($gid) {
316
		$this->fixDI();
317
318
		// Check cache first
319
		if (isset($this->groupCache[$gid])) {
320
			return true;
321
		}
322
323
		$qb = $this->dbConn->getQueryBuilder();
324
		$cursor = $qb->select('gid', 'displayname')
325
			->from('groups')
326
			->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
327
			->execute();
328
		$result = $cursor->fetch();
329
		$cursor->closeCursor();
330
331
		if ($result !== false) {
332
			$this->groupCache[$gid] = [
333
				'gid' => $gid,
334
				'displayname' => $result['displayname'],
335
			];
336
			return true;
337
		}
338
		return false;
339
	}
340
341
	/**
342
	 * get a list of all users in a group
343
	 * @param string $gid
344
	 * @param string $search
345
	 * @param int $limit
346
	 * @param int $offset
347
	 * @return array an array of user ids
348
	 */
349
	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
350
		$this->fixDI();
351
352
		$query = $this->dbConn->getQueryBuilder();
353
		$query->select('g.uid')
354
			->from('group_user', 'g')
355
			->where($query->expr()->eq('gid', $query->createNamedParameter($gid)))
356
			->orderBy('g.uid', 'ASC');
357
358
		if ($search !== '') {
359
			$query->leftJoin('g', 'users', 'u', $query->expr()->eq('g.uid', 'u.uid'))
360
				->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
361
					$query->expr()->eq('p.userid', 'u.uid'),
362
					$query->expr()->eq('p.appid', $query->expr()->literal('settings')),
363
					$query->expr()->eq('p.configkey', $query->expr()->literal('email')))
364
				)
365
				// sqlite doesn't like re-using a single named parameter here
366
				->andWhere(
367
					$query->expr()->orX(
368
						$query->expr()->ilike('g.uid', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')),
369
						$query->expr()->ilike('u.displayname', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')),
370
						$query->expr()->ilike('p.configvalue', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%'))
371
					)
372
				)
373
				->orderBy('u.uid_lower', 'ASC');
374
		}
375
376
		if ($limit !== -1) {
377
			$query->setMaxResults($limit);
378
		}
379
		if ($offset !== 0) {
380
			$query->setFirstResult($offset);
381
		}
382
383
		$result = $query->execute();
384
385
		$users = [];
386
		while ($row = $result->fetch()) {
387
			$users[] = $row['uid'];
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
			return $this->groupCache[$gid]['displayname'];
462
		}
463
464
		$this->fixDI();
465
466
		$query = $this->dbConn->getQueryBuilder();
467
		$query->select('displayname')
468
			->from('groups')
469
			->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
470
471
		$result = $query->execute();
472
		$displayName = $result->fetchOne();
473
		$result->closeCursor();
474
475
		return (string) $displayName;
476
	}
477
478
	public function getGroupDetails(string $gid): array {
479
		$displayName = $this->getDisplayName($gid);
480
		if ($displayName !== '') {
481
			return ['displayName' => $displayName];
482
		}
483
484
		return [];
485
	}
486
487
	public function setDisplayName(string $gid, string $displayName): bool {
488
		if (!$this->groupExists($gid)) {
489
			return false;
490
		}
491
492
		$this->fixDI();
493
494
		$displayName = trim($displayName);
495
		if ($displayName === '') {
496
			$displayName = $gid;
497
		}
498
499
		$query = $this->dbConn->getQueryBuilder();
500
		$query->update('groups')
501
			->set('displayname', $query->createNamedParameter($displayName))
502
			->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
503
		$query->execute();
504
505
		return true;
506
	}
507
508
	/**
509
	 * Backend name to be shown in group management
510
	 * @return string the name of the backend to be shown
511
	 * @since 21.0.0
512
	 */
513
	public function getBackendName(): string {
514
		return 'Database';
515
	}
516
}
517