Database.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Group;
  8. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  9. use OC\User\LazyUser;
  10. use OCP\DB\QueryBuilder\IQueryBuilder;
  11. use OCP\Group\Backend\ABackend;
  12. use OCP\Group\Backend\IAddToGroupBackend;
  13. use OCP\Group\Backend\IBatchMethodsBackend;
  14. use OCP\Group\Backend\ICountDisabledInGroup;
  15. use OCP\Group\Backend\ICountUsersBackend;
  16. use OCP\Group\Backend\ICreateNamedGroupBackend;
  17. use OCP\Group\Backend\IDeleteGroupBackend;
  18. use OCP\Group\Backend\IGetDisplayNameBackend;
  19. use OCP\Group\Backend\IGroupDetailsBackend;
  20. use OCP\Group\Backend\INamedBackend;
  21. use OCP\Group\Backend\IRemoveFromGroupBackend;
  22. use OCP\Group\Backend\ISearchableGroupBackend;
  23. use OCP\Group\Backend\ISetDisplayNameBackend;
  24. use OCP\IDBConnection;
  25. use OCP\IUserManager;
  26. /**
  27. * Class for group management in a SQL Database (e.g. MySQL, SQLite)
  28. */
  29. class Database extends ABackend implements
  30. IAddToGroupBackend,
  31. ICountDisabledInGroup,
  32. ICountUsersBackend,
  33. ICreateNamedGroupBackend,
  34. IDeleteGroupBackend,
  35. IGetDisplayNameBackend,
  36. IGroupDetailsBackend,
  37. IRemoveFromGroupBackend,
  38. ISetDisplayNameBackend,
  39. ISearchableGroupBackend,
  40. IBatchMethodsBackend,
  41. INamedBackend {
  42. /** @var array<string, array{gid: string, displayname: string}> */
  43. private $groupCache = [];
  44. private ?IDBConnection $dbConn;
  45. /**
  46. * \OC\Group\Database constructor.
  47. *
  48. * @param IDBConnection|null $dbConn
  49. */
  50. public function __construct(?IDBConnection $dbConn = null) {
  51. $this->dbConn = $dbConn;
  52. }
  53. /**
  54. * FIXME: This function should not be required!
  55. */
  56. private function fixDI() {
  57. if ($this->dbConn === null) {
  58. $this->dbConn = \OC::$server->getDatabaseConnection();
  59. }
  60. }
  61. public function createGroup(string $name): ?string {
  62. $this->fixDI();
  63. $gid = $this->computeGid($name);
  64. try {
  65. // Add group
  66. $builder = $this->dbConn->getQueryBuilder();
  67. $result = $builder->insert('groups')
  68. ->setValue('gid', $builder->createNamedParameter($gid))
  69. ->setValue('displayname', $builder->createNamedParameter($name))
  70. ->execute();
  71. } catch (UniqueConstraintViolationException $e) {
  72. return null;
  73. }
  74. // Add to cache
  75. $this->groupCache[$gid] = [
  76. 'gid' => $gid,
  77. 'displayname' => $name
  78. ];
  79. return $gid;
  80. }
  81. /**
  82. * delete a group
  83. * @param string $gid gid of the group to delete
  84. * @return bool
  85. *
  86. * Deletes a group and removes it from the group_user-table
  87. */
  88. public function deleteGroup(string $gid): bool {
  89. $this->fixDI();
  90. // Delete the group
  91. $qb = $this->dbConn->getQueryBuilder();
  92. $qb->delete('groups')
  93. ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
  94. ->execute();
  95. // Delete the group-user relation
  96. $qb = $this->dbConn->getQueryBuilder();
  97. $qb->delete('group_user')
  98. ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
  99. ->execute();
  100. // Delete the group-groupadmin relation
  101. $qb = $this->dbConn->getQueryBuilder();
  102. $qb->delete('group_admin')
  103. ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
  104. ->execute();
  105. // Delete from cache
  106. unset($this->groupCache[$gid]);
  107. return true;
  108. }
  109. /**
  110. * is user in group?
  111. * @param string $uid uid of the user
  112. * @param string $gid gid of the group
  113. * @return bool
  114. *
  115. * Checks whether the user is member of a group or not.
  116. */
  117. public function inGroup($uid, $gid) {
  118. $this->fixDI();
  119. // check
  120. $qb = $this->dbConn->getQueryBuilder();
  121. $cursor = $qb->select('uid')
  122. ->from('group_user')
  123. ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
  124. ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  125. ->execute();
  126. $result = $cursor->fetch();
  127. $cursor->closeCursor();
  128. return $result ? true : false;
  129. }
  130. /**
  131. * Add a user to a group
  132. * @param string $uid Name of the user to add to group
  133. * @param string $gid Name of the group in which add the user
  134. * @return bool
  135. *
  136. * Adds a user to a group.
  137. */
  138. public function addToGroup(string $uid, string $gid): bool {
  139. $this->fixDI();
  140. // No duplicate entries!
  141. if (!$this->inGroup($uid, $gid)) {
  142. $qb = $this->dbConn->getQueryBuilder();
  143. $qb->insert('group_user')
  144. ->setValue('uid', $qb->createNamedParameter($uid))
  145. ->setValue('gid', $qb->createNamedParameter($gid))
  146. ->execute();
  147. return true;
  148. } else {
  149. return false;
  150. }
  151. }
  152. /**
  153. * Removes a user from a group
  154. * @param string $uid Name of the user to remove from group
  155. * @param string $gid Name of the group from which remove the user
  156. * @return bool
  157. *
  158. * removes the user from a group.
  159. */
  160. public function removeFromGroup(string $uid, string $gid): bool {
  161. $this->fixDI();
  162. $qb = $this->dbConn->getQueryBuilder();
  163. $qb->delete('group_user')
  164. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  165. ->andWhere($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
  166. ->execute();
  167. return true;
  168. }
  169. /**
  170. * Get all groups a user belongs to
  171. * @param string $uid Name of the user
  172. * @return array an array of group names
  173. *
  174. * This function fetches all groups a user belongs to. It does not check
  175. * if the user exists at all.
  176. */
  177. public function getUserGroups($uid) {
  178. //guests has empty or null $uid
  179. if ($uid === null || $uid === '') {
  180. return [];
  181. }
  182. $this->fixDI();
  183. // No magic!
  184. $qb = $this->dbConn->getQueryBuilder();
  185. $cursor = $qb->select('gu.gid', 'g.displayname')
  186. ->from('group_user', 'gu')
  187. ->leftJoin('gu', 'groups', 'g', $qb->expr()->eq('gu.gid', 'g.gid'))
  188. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  189. ->execute();
  190. $groups = [];
  191. while ($row = $cursor->fetch()) {
  192. $groups[] = $row['gid'];
  193. $this->groupCache[$row['gid']] = [
  194. 'gid' => $row['gid'],
  195. 'displayname' => $row['displayname'],
  196. ];
  197. }
  198. $cursor->closeCursor();
  199. return $groups;
  200. }
  201. /**
  202. * get a list of all groups
  203. * @param string $search
  204. * @param int $limit
  205. * @param int $offset
  206. * @return array an array of group names
  207. *
  208. * Returns a list with all groups
  209. */
  210. public function getGroups(string $search = '', int $limit = -1, int $offset = 0) {
  211. $this->fixDI();
  212. $query = $this->dbConn->getQueryBuilder();
  213. $query->select('gid', 'displayname')
  214. ->from('groups')
  215. ->orderBy('gid', 'ASC');
  216. if ($search !== '') {
  217. $query->where($query->expr()->iLike('gid', $query->createNamedParameter(
  218. '%' . $this->dbConn->escapeLikeParameter($search) . '%'
  219. )));
  220. $query->orWhere($query->expr()->iLike('displayname', $query->createNamedParameter(
  221. '%' . $this->dbConn->escapeLikeParameter($search) . '%'
  222. )));
  223. }
  224. if ($limit > 0) {
  225. $query->setMaxResults($limit);
  226. }
  227. if ($offset > 0) {
  228. $query->setFirstResult($offset);
  229. }
  230. $result = $query->execute();
  231. $groups = [];
  232. while ($row = $result->fetch()) {
  233. $this->groupCache[$row['gid']] = [
  234. 'displayname' => $row['displayname'],
  235. 'gid' => $row['gid'],
  236. ];
  237. $groups[] = $row['gid'];
  238. }
  239. $result->closeCursor();
  240. return $groups;
  241. }
  242. /**
  243. * check if a group exists
  244. * @param string $gid
  245. * @return bool
  246. */
  247. public function groupExists($gid) {
  248. $this->fixDI();
  249. // Check cache first
  250. if (isset($this->groupCache[$gid])) {
  251. return true;
  252. }
  253. $qb = $this->dbConn->getQueryBuilder();
  254. $cursor = $qb->select('gid', 'displayname')
  255. ->from('groups')
  256. ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
  257. ->execute();
  258. $result = $cursor->fetch();
  259. $cursor->closeCursor();
  260. if ($result !== false) {
  261. $this->groupCache[$gid] = [
  262. 'gid' => $gid,
  263. 'displayname' => $result['displayname'],
  264. ];
  265. return true;
  266. }
  267. return false;
  268. }
  269. /**
  270. * {@inheritdoc}
  271. */
  272. public function groupsExists(array $gids): array {
  273. $notFoundGids = [];
  274. $existingGroups = [];
  275. // In case the data is already locally accessible, not need to do SQL query
  276. // or do a SQL query but with a smaller in clause
  277. foreach ($gids as $gid) {
  278. if (isset($this->groupCache[$gid])) {
  279. $existingGroups[] = $gid;
  280. } else {
  281. $notFoundGids[] = $gid;
  282. }
  283. }
  284. $qb = $this->dbConn->getQueryBuilder();
  285. $qb->select('gid', 'displayname')
  286. ->from('groups')
  287. ->where($qb->expr()->in('gid', $qb->createParameter('ids')));
  288. foreach (array_chunk($notFoundGids, 1000) as $chunk) {
  289. $qb->setParameter('ids', $chunk, IQueryBuilder::PARAM_STR_ARRAY);
  290. $result = $qb->executeQuery();
  291. while ($row = $result->fetch()) {
  292. $this->groupCache[(string)$row['gid']] = [
  293. 'displayname' => (string)$row['displayname'],
  294. 'gid' => (string)$row['gid'],
  295. ];
  296. $existingGroups[] = (string)$row['gid'];
  297. }
  298. $result->closeCursor();
  299. }
  300. return $existingGroups;
  301. }
  302. /**
  303. * Get a list of all users in a group
  304. * @param string $gid
  305. * @param string $search
  306. * @param int $limit
  307. * @param int $offset
  308. * @return array<int,string> an array of user ids
  309. */
  310. public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0): array {
  311. return array_values(array_map(fn ($user) => $user->getUid(), $this->searchInGroup($gid, $search, $limit, $offset)));
  312. }
  313. public function searchInGroup(string $gid, string $search = '', int $limit = -1, int $offset = 0): array {
  314. $this->fixDI();
  315. $query = $this->dbConn->getQueryBuilder();
  316. $query->select('g.uid', 'u.displayname');
  317. $query->from('group_user', 'g')
  318. ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)))
  319. ->orderBy('g.uid', 'ASC');
  320. $query->leftJoin('g', 'users', 'u', $query->expr()->eq('g.uid', 'u.uid'));
  321. if ($search !== '') {
  322. $query->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
  323. $query->expr()->eq('p.userid', 'u.uid'),
  324. $query->expr()->eq('p.appid', $query->expr()->literal('settings')),
  325. $query->expr()->eq('p.configkey', $query->expr()->literal('email'))
  326. ))
  327. // sqlite doesn't like re-using a single named parameter here
  328. ->andWhere(
  329. $query->expr()->orX(
  330. $query->expr()->ilike('g.uid', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')),
  331. $query->expr()->ilike('u.displayname', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')),
  332. $query->expr()->ilike('p.configvalue', $query->createNamedParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%'))
  333. )
  334. )
  335. ->orderBy('u.uid_lower', 'ASC');
  336. }
  337. if ($limit !== -1) {
  338. $query->setMaxResults($limit);
  339. }
  340. if ($offset !== 0) {
  341. $query->setFirstResult($offset);
  342. }
  343. $result = $query->executeQuery();
  344. $users = [];
  345. $userManager = \OCP\Server::get(IUserManager::class);
  346. while ($row = $result->fetch()) {
  347. $users[$row['uid']] = new LazyUser($row['uid'], $userManager, $row['displayname'] ?? null);
  348. }
  349. $result->closeCursor();
  350. return $users;
  351. }
  352. /**
  353. * get the number of all users matching the search string in a group
  354. * @param string $gid
  355. * @param string $search
  356. * @return int
  357. */
  358. public function countUsersInGroup(string $gid, string $search = ''): int {
  359. $this->fixDI();
  360. $query = $this->dbConn->getQueryBuilder();
  361. $query->select($query->func()->count('*', 'num_users'))
  362. ->from('group_user')
  363. ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
  364. if ($search !== '') {
  365. $query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
  366. '%' . $this->dbConn->escapeLikeParameter($search) . '%'
  367. )));
  368. }
  369. $result = $query->execute();
  370. $count = $result->fetchOne();
  371. $result->closeCursor();
  372. if ($count !== false) {
  373. $count = (int)$count;
  374. } else {
  375. $count = 0;
  376. }
  377. return $count;
  378. }
  379. /**
  380. * get the number of disabled users in a group
  381. *
  382. * @param string $search
  383. *
  384. * @return int
  385. */
  386. public function countDisabledInGroup(string $gid): int {
  387. $this->fixDI();
  388. $query = $this->dbConn->getQueryBuilder();
  389. $query->select($query->createFunction('COUNT(DISTINCT ' . $query->getColumnName('uid') . ')'))
  390. ->from('preferences', 'p')
  391. ->innerJoin('p', 'group_user', 'g', $query->expr()->eq('p.userid', 'g.uid'))
  392. ->where($query->expr()->eq('appid', $query->createNamedParameter('core')))
  393. ->andWhere($query->expr()->eq('configkey', $query->createNamedParameter('enabled')))
  394. ->andWhere($query->expr()->eq('configvalue', $query->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
  395. ->andWhere($query->expr()->eq('gid', $query->createNamedParameter($gid), IQueryBuilder::PARAM_STR));
  396. $result = $query->execute();
  397. $count = $result->fetchOne();
  398. $result->closeCursor();
  399. if ($count !== false) {
  400. $count = (int)$count;
  401. } else {
  402. $count = 0;
  403. }
  404. return $count;
  405. }
  406. public function getDisplayName(string $gid): string {
  407. if (isset($this->groupCache[$gid])) {
  408. $displayName = $this->groupCache[$gid]['displayname'];
  409. if (isset($displayName) && trim($displayName) !== '') {
  410. return $displayName;
  411. }
  412. }
  413. $this->fixDI();
  414. $query = $this->dbConn->getQueryBuilder();
  415. $query->select('displayname')
  416. ->from('groups')
  417. ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
  418. $result = $query->execute();
  419. $displayName = $result->fetchOne();
  420. $result->closeCursor();
  421. return (string) $displayName;
  422. }
  423. public function getGroupDetails(string $gid): array {
  424. $displayName = $this->getDisplayName($gid);
  425. if ($displayName !== '') {
  426. return ['displayName' => $displayName];
  427. }
  428. return [];
  429. }
  430. /**
  431. * {@inheritdoc}
  432. */
  433. public function getGroupsDetails(array $gids): array {
  434. $notFoundGids = [];
  435. $details = [];
  436. $this->fixDI();
  437. // In case the data is already locally accessible, not need to do SQL query
  438. // or do a SQL query but with a smaller in clause
  439. foreach ($gids as $gid) {
  440. if (isset($this->groupCache[$gid])) {
  441. $details[$gid] = ['displayName' => $this->groupCache[$gid]['displayname']];
  442. } else {
  443. $notFoundGids[] = $gid;
  444. }
  445. }
  446. foreach (array_chunk($notFoundGids, 1000) as $chunk) {
  447. $query = $this->dbConn->getQueryBuilder();
  448. $query->select('gid', 'displayname')
  449. ->from('groups')
  450. ->where($query->expr()->in('gid', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY)));
  451. $result = $query->executeQuery();
  452. while ($row = $result->fetch()) {
  453. $details[(string)$row['gid']] = ['displayName' => (string)$row['displayname']];
  454. $this->groupCache[(string)$row['gid']] = [
  455. 'displayname' => (string)$row['displayname'],
  456. 'gid' => (string)$row['gid'],
  457. ];
  458. }
  459. $result->closeCursor();
  460. }
  461. return $details;
  462. }
  463. public function setDisplayName(string $gid, string $displayName): bool {
  464. if (!$this->groupExists($gid)) {
  465. return false;
  466. }
  467. $this->fixDI();
  468. $displayName = trim($displayName);
  469. if ($displayName === '') {
  470. $displayName = $gid;
  471. }
  472. $query = $this->dbConn->getQueryBuilder();
  473. $query->update('groups')
  474. ->set('displayname', $query->createNamedParameter($displayName))
  475. ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
  476. $query->execute();
  477. return true;
  478. }
  479. /**
  480. * Backend name to be shown in group management
  481. * @return string the name of the backend to be shown
  482. * @since 21.0.0
  483. */
  484. public function getBackendName(): string {
  485. return 'Database';
  486. }
  487. /**
  488. * Compute group ID from display name (GIDs are limited to 64 characters in database)
  489. */
  490. private function computeGid(string $displayName): string {
  491. return mb_strlen($displayName) > 64
  492. ? hash('sha256', $displayName)
  493. : $displayName;
  494. }
  495. }