1
0

Database.php 16 KB

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