Database.php 14 KB

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