1
0

Database.php 16 KB

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