You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

505 lines
13 KiB

3 years ago
  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 John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  8. * @author Loki3000 <github@labcms.ru>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. /*
  28. *
  29. * The following SQL statement is just a help for developers and will not be
  30. * executed!
  31. *
  32. * CREATE TABLE `groups` (
  33. * `gid` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  34. * PRIMARY KEY (`gid`)
  35. * ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  36. *
  37. * CREATE TABLE `group_user` (
  38. * `gid` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  39. * `uid` varchar(64) COLLATE utf8_unicode_ci NOT NULL
  40. * ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  41. *
  42. */
  43. namespace OC\Group;
  44. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  45. use OCP\DB\QueryBuilder\IQueryBuilder;
  46. use OCP\Group\Backend\ABackend;
  47. use OCP\Group\Backend\IAddToGroupBackend;
  48. use OCP\Group\Backend\ICountDisabledInGroup;
  49. use OCP\Group\Backend\ICountUsersBackend;
  50. use OCP\Group\Backend\ICreateGroupBackend;
  51. use OCP\Group\Backend\IDeleteGroupBackend;
  52. use OCP\Group\Backend\IGetDisplayNameBackend;
  53. use OCP\Group\Backend\IGroupDetailsBackend;
  54. use OCP\Group\Backend\IRemoveFromGroupBackend;
  55. use OCP\Group\Backend\ISetDisplayNameBackend;
  56. use OCP\IDBConnection;
  57. /**
  58. * Class for group management in a SQL Database (e.g. MySQL, SQLite)
  59. */
  60. class Database extends ABackend implements
  61. IAddToGroupBackend,
  62. ICountDisabledInGroup,
  63. ICountUsersBackend,
  64. ICreateGroupBackend,
  65. IDeleteGroupBackend,
  66. IGetDisplayNameBackend,
  67. IGroupDetailsBackend,
  68. IRemoveFromGroupBackend,
  69. ISetDisplayNameBackend {
  70. /** @var string[] */
  71. private $groupCache = [];
  72. /** @var IDBConnection */
  73. private $dbConn;
  74. /**
  75. * \OC\Group\Database constructor.
  76. *
  77. * @param IDBConnection|null $dbConn
  78. */
  79. public function __construct(IDBConnection $dbConn = null) {
  80. $this->dbConn = $dbConn;
  81. }
  82. /**
  83. * FIXME: This function should not be required!
  84. */
  85. private function fixDI() {
  86. if ($this->dbConn === null) {
  87. $this->dbConn = \OC::$server->getDatabaseConnection();
  88. }
  89. }
  90. /**
  91. * Try to create a new group
  92. * @param string $gid The name of the group to create
  93. * @return bool
  94. *
  95. * Tries to create a new group. If the group name already exists, false will
  96. * be returned.
  97. */
  98. public function createGroup(string $gid): bool {
  99. $this->fixDI();
  100. try {
  101. // Add group
  102. $builder = $this->dbConn->getQueryBuilder();
  103. $result = $builder->insert('groups')
  104. ->setValue('gid', $builder->createNamedParameter($gid))
  105. ->setValue('displayname', $builder->createNamedParameter($gid))
  106. ->execute();
  107. } catch (UniqueConstraintViolationException $e) {
  108. $result = 0;
  109. }
  110. // Add to cache
  111. $this->groupCache[$gid] = [
  112. 'gid' => $gid,
  113. 'displayname' => $gid
  114. ];
  115. return $result === 1;
  116. }
  117. /**
  118. * delete a group
  119. * @param string $gid gid of the group to delete
  120. * @return bool
  121. *
  122. * Deletes a group and removes it from the group_user-table
  123. */
  124. public function deleteGroup(string $gid): bool {
  125. $this->fixDI();
  126. // Delete the group
  127. $qb = $this->dbConn->getQueryBuilder();
  128. $qb->delete('groups')
  129. ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
  130. ->execute();
  131. // Delete the group-user relation
  132. $qb = $this->dbConn->getQueryBuilder();
  133. $qb->delete('group_user')
  134. ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
  135. ->execute();
  136. // Delete the group-groupadmin relation
  137. $qb = $this->dbConn->getQueryBuilder();
  138. $qb->delete('group_admin')
  139. ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
  140. ->execute();
  141. // Delete from cache
  142. unset($this->groupCache[$gid]);
  143. return true;
  144. }
  145. /**
  146. * is user in group?
  147. * @param string $uid uid of the user
  148. * @param string $gid gid of the group
  149. * @return bool
  150. *
  151. * Checks whether the user is member of a group or not.
  152. */
  153. public function inGroup($uid, $gid) {
  154. $this->fixDI();
  155. // check
  156. $qb = $this->dbConn->getQueryBuilder();
  157. $cursor = $qb->select('uid')
  158. ->from('group_user')
  159. ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
  160. ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  161. ->execute();
  162. $result = $cursor->fetch();
  163. $cursor->closeCursor();
  164. return $result ? true : false;
  165. }
  166. /**
  167. * Add a user to a group
  168. * @param string $uid Name of the user to add to group
  169. * @param string $gid Name of the group in which add the user
  170. * @return bool
  171. *
  172. * Adds a user to a group.
  173. */
  174. public function addToGroup(string $uid, string $gid): bool {
  175. $this->fixDI();
  176. // No duplicate entries!
  177. if (!$this->inGroup($uid, $gid)) {
  178. $qb = $this->dbConn->getQueryBuilder();
  179. $qb->insert('group_user')
  180. ->setValue('uid', $qb->createNamedParameter($uid))
  181. ->setValue('gid', $qb->createNamedParameter($gid))
  182. ->execute();
  183. return true;
  184. } else {
  185. return false;
  186. }
  187. }
  188. /**
  189. * Removes a user from a group
  190. * @param string $uid Name of the user to remove from group
  191. * @param string $gid Name of the group from which remove the user
  192. * @return bool
  193. *
  194. * removes the user from a group.
  195. */
  196. public function removeFromGroup(string $uid, string $gid): bool {
  197. $this->fixDI();
  198. $qb = $this->dbConn->getQueryBuilder();
  199. $qb->delete('group_user')
  200. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  201. ->andWhere($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
  202. ->execute();
  203. return true;
  204. }
  205. /**
  206. * Get all groups a user belongs to
  207. * @param string $uid Name of the user
  208. * @return array an array of group names
  209. *
  210. * This function fetches all groups a user belongs to. It does not check
  211. * if the user exists at all.
  212. */
  213. public function getUserGroups($uid) {
  214. //guests has empty or null $uid
  215. if ($uid === null || $uid === '') {
  216. return [];
  217. }
  218. $this->fixDI();
  219. // No magic!
  220. $qb = $this->dbConn->getQueryBuilder();
  221. $cursor = $qb->select('gu.gid', 'g.displayname')
  222. ->from('group_user', 'gu')
  223. ->leftJoin('gu', 'groups', 'g', $qb->expr()->eq('gu.gid', 'g.gid'))
  224. ->where($qb->expr()->eq('uid', $qb->createNamedParameter($uid)))
  225. ->execute();
  226. $groups = [];
  227. while ($row = $cursor->fetch()) {
  228. $groups[] = $row['gid'];
  229. $this->groupCache[$row['gid']] = [
  230. 'gid' => $row['gid'],
  231. 'displayname' => $row['displayname'],
  232. ];
  233. }
  234. $cursor->closeCursor();
  235. return $groups;
  236. }
  237. /**
  238. * get a list of all groups
  239. * @param string $search
  240. * @param int $limit
  241. * @param int $offset
  242. * @return array an array of group names
  243. *
  244. * Returns a list with all groups
  245. */
  246. public function getGroups($search = '', $limit = null, $offset = null) {
  247. $this->fixDI();
  248. $query = $this->dbConn->getQueryBuilder();
  249. $query->select('gid')
  250. ->from('groups')
  251. ->orderBy('gid', 'ASC');
  252. if ($search !== '') {
  253. $query->where($query->expr()->iLike('gid', $query->createNamedParameter(
  254. '%' . $this->dbConn->escapeLikeParameter($search) . '%'
  255. )));
  256. $query->orWhere($query->expr()->iLike('displayname', $query->createNamedParameter(
  257. '%' . $this->dbConn->escapeLikeParameter($search) . '%'
  258. )));
  259. }
  260. $query->setMaxResults($limit)
  261. ->setFirstResult($offset);
  262. $result = $query->execute();
  263. $groups = [];
  264. while ($row = $result->fetch()) {
  265. $groups[] = $row['gid'];
  266. }
  267. $result->closeCursor();
  268. return $groups;
  269. }
  270. /**
  271. * check if a group exists
  272. * @param string $gid
  273. * @return bool
  274. */
  275. public function groupExists($gid) {
  276. $this->fixDI();
  277. // Check cache first
  278. if (isset($this->groupCache[$gid])) {
  279. return true;
  280. }
  281. $qb = $this->dbConn->getQueryBuilder();
  282. $cursor = $qb->select('gid', 'displayname')
  283. ->from('groups')
  284. ->where($qb->expr()->eq('gid', $qb->createNamedParameter($gid)))
  285. ->execute();
  286. $result = $cursor->fetch();
  287. $cursor->closeCursor();
  288. if ($result !== false) {
  289. $this->groupCache[$gid] = [
  290. 'gid' => $gid,
  291. 'displayname' => $result['displayname'],
  292. ];
  293. return true;
  294. }
  295. return false;
  296. }
  297. /**
  298. * get a list of all users in a group
  299. * @param string $gid
  300. * @param string $search
  301. * @param int $limit
  302. * @param int $offset
  303. * @return array an array of user ids
  304. */
  305. public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
  306. $this->fixDI();
  307. $query = $this->dbConn->getQueryBuilder();
  308. $query->select('g.uid')
  309. ->from('group_user', 'g')
  310. ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)))
  311. ->orderBy('g.uid', 'ASC');
  312. if ($search !== '') {
  313. $query->leftJoin('g', 'users', 'u', $query->expr()->eq('g.uid', 'u.uid'))
  314. ->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->execute();
  336. $users = [];
  337. while ($row = $result->fetch()) {
  338. $users[] = $row['uid'];
  339. }
  340. $result->closeCursor();
  341. return $users;
  342. }
  343. /**
  344. * get the number of all users matching the search string in a group
  345. * @param string $gid
  346. * @param string $search
  347. * @return int
  348. */
  349. public function countUsersInGroup(string $gid, string $search = ''): int {
  350. $this->fixDI();
  351. $query = $this->dbConn->getQueryBuilder();
  352. $query->select($query->func()->count('*', 'num_users'))
  353. ->from('group_user')
  354. ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
  355. if ($search !== '') {
  356. $query->andWhere($query->expr()->like('uid', $query->createNamedParameter(
  357. '%' . $this->dbConn->escapeLikeParameter($search) . '%'
  358. )));
  359. }
  360. $result = $query->execute();
  361. $count = $result->fetchColumn();
  362. $result->closeCursor();
  363. if ($count !== false) {
  364. $count = (int)$count;
  365. } else {
  366. $count = 0;
  367. }
  368. return $count;
  369. }
  370. /**
  371. * get the number of disabled users in a group
  372. *
  373. * @param string $search
  374. *
  375. * @return int
  376. */
  377. public function countDisabledInGroup(string $gid): int {
  378. $this->fixDI();
  379. $query = $this->dbConn->getQueryBuilder();
  380. $query->select($query->createFunction('COUNT(DISTINCT ' . $query->getColumnName('uid') . ')'))
  381. ->from('preferences', 'p')
  382. ->innerJoin('p', 'group_user', 'g', $query->expr()->eq('p.userid', 'g.uid'))
  383. ->where($query->expr()->eq('appid', $query->createNamedParameter('core')))
  384. ->andWhere($query->expr()->eq('configkey', $query->createNamedParameter('enabled')))
  385. ->andWhere($query->expr()->eq('configvalue', $query->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
  386. ->andWhere($query->expr()->eq('gid', $query->createNamedParameter($gid), IQueryBuilder::PARAM_STR));
  387. $result = $query->execute();
  388. $count = $result->fetchColumn();
  389. $result->closeCursor();
  390. if ($count !== false) {
  391. $count = (int)$count;
  392. } else {
  393. $count = 0;
  394. }
  395. return $count;
  396. }
  397. public function getDisplayName(string $gid): string {
  398. if (isset($this->groupCache[$gid])) {
  399. return $this->groupCache[$gid]['displayname'];
  400. }
  401. $this->fixDI();
  402. $query = $this->dbConn->getQueryBuilder();
  403. $query->select('displayname')
  404. ->from('groups')
  405. ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
  406. $result = $query->execute();
  407. $displayName = $result->fetchColumn();
  408. $result->closeCursor();
  409. return (string) $displayName;
  410. }
  411. public function getGroupDetails(string $gid): array {
  412. $displayName = $this->getDisplayName($gid);
  413. if ($displayName !== '') {
  414. return ['displayName' => $displayName];
  415. }
  416. return [];
  417. }
  418. public function setDisplayName(string $gid, string $displayName): bool {
  419. if (!$this->groupExists($gid)) {
  420. return false;
  421. }
  422. $this->fixDI();
  423. $displayName = trim($displayName);
  424. if ($displayName === '') {
  425. $displayName = $gid;
  426. }
  427. $query = $this->dbConn->getQueryBuilder();
  428. $query->update('groups')
  429. ->set('displayname', $query->createNamedParameter($displayName))
  430. ->where($query->expr()->eq('gid', $query->createNamedParameter($gid)));
  431. $query->execute();
  432. return true;
  433. }
  434. }