Database.php 14 KB

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