Manager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Group;
  8. use OC\Hooks\PublicEmitter;
  9. use OCP\EventDispatcher\IEventDispatcher;
  10. use OCP\Group\Backend\IBatchMethodsBackend;
  11. use OCP\Group\Backend\ICreateNamedGroupBackend;
  12. use OCP\Group\Backend\IGroupDetailsBackend;
  13. use OCP\Group\Events\BeforeGroupCreatedEvent;
  14. use OCP\Group\Events\GroupCreatedEvent;
  15. use OCP\GroupInterface;
  16. use OCP\ICacheFactory;
  17. use OCP\IGroup;
  18. use OCP\IGroupManager;
  19. use OCP\IUser;
  20. use Psr\Log\LoggerInterface;
  21. use function is_string;
  22. /**
  23. * Class Manager
  24. *
  25. * Hooks available in scope \OC\Group:
  26. * - preAddUser(\OC\Group\Group $group, \OC\User\User $user)
  27. * - postAddUser(\OC\Group\Group $group, \OC\User\User $user)
  28. * - preRemoveUser(\OC\Group\Group $group, \OC\User\User $user)
  29. * - postRemoveUser(\OC\Group\Group $group, \OC\User\User $user)
  30. * - preDelete(\OC\Group\Group $group)
  31. * - postDelete(\OC\Group\Group $group)
  32. * - preCreate(string $groupId)
  33. * - postCreate(\OC\Group\Group $group)
  34. *
  35. * @package OC\Group
  36. */
  37. class Manager extends PublicEmitter implements IGroupManager {
  38. /** @var GroupInterface[] */
  39. private $backends = [];
  40. /** @var \OC\User\Manager */
  41. private $userManager;
  42. private IEventDispatcher $dispatcher;
  43. private LoggerInterface $logger;
  44. /** @var array<string, IGroup> */
  45. private $cachedGroups = [];
  46. /** @var array<string, list<string>> */
  47. private $cachedUserGroups = [];
  48. /** @var \OC\SubAdmin */
  49. private $subAdmin = null;
  50. private DisplayNameCache $displayNameCache;
  51. private const MAX_GROUP_LENGTH = 255;
  52. public function __construct(\OC\User\Manager $userManager,
  53. IEventDispatcher $dispatcher,
  54. LoggerInterface $logger,
  55. ICacheFactory $cacheFactory) {
  56. $this->userManager = $userManager;
  57. $this->dispatcher = $dispatcher;
  58. $this->logger = $logger;
  59. $this->displayNameCache = new DisplayNameCache($cacheFactory, $this);
  60. $this->listen('\OC\Group', 'postDelete', function (IGroup $group): void {
  61. unset($this->cachedGroups[$group->getGID()]);
  62. $this->cachedUserGroups = [];
  63. });
  64. $this->listen('\OC\Group', 'postAddUser', function (IGroup $group): void {
  65. $this->cachedUserGroups = [];
  66. });
  67. $this->listen('\OC\Group', 'postRemoveUser', function (IGroup $group): void {
  68. $this->cachedUserGroups = [];
  69. });
  70. }
  71. /**
  72. * Checks whether a given backend is used
  73. *
  74. * @param string $backendClass Full classname including complete namespace
  75. * @return bool
  76. */
  77. public function isBackendUsed($backendClass) {
  78. $backendClass = strtolower(ltrim($backendClass, '\\'));
  79. foreach ($this->backends as $backend) {
  80. if (strtolower(get_class($backend)) === $backendClass) {
  81. return true;
  82. }
  83. }
  84. return false;
  85. }
  86. /**
  87. * @param \OCP\GroupInterface $backend
  88. */
  89. public function addBackend($backend) {
  90. $this->backends[] = $backend;
  91. $this->clearCaches();
  92. }
  93. public function clearBackends() {
  94. $this->backends = [];
  95. $this->clearCaches();
  96. }
  97. /**
  98. * Get the active backends
  99. *
  100. * @return \OCP\GroupInterface[]
  101. */
  102. public function getBackends() {
  103. return $this->backends;
  104. }
  105. protected function clearCaches() {
  106. $this->cachedGroups = [];
  107. $this->cachedUserGroups = [];
  108. }
  109. /**
  110. * @param string $gid
  111. * @return IGroup|null
  112. */
  113. public function get($gid) {
  114. if (isset($this->cachedGroups[$gid])) {
  115. return $this->cachedGroups[$gid];
  116. }
  117. return $this->getGroupObject($gid);
  118. }
  119. /**
  120. * @param string $gid
  121. * @param string $displayName
  122. * @return \OCP\IGroup|null
  123. */
  124. protected function getGroupObject($gid, $displayName = null) {
  125. $backends = [];
  126. foreach ($this->backends as $backend) {
  127. if ($backend->implementsActions(Backend::GROUP_DETAILS)) {
  128. $groupData = $backend->getGroupDetails($gid);
  129. if (is_array($groupData) && !empty($groupData)) {
  130. // take the display name from the last backend that has a non-null one
  131. if (is_null($displayName) && isset($groupData['displayName'])) {
  132. $displayName = $groupData['displayName'];
  133. }
  134. $backends[] = $backend;
  135. }
  136. } elseif ($backend->groupExists($gid)) {
  137. $backends[] = $backend;
  138. }
  139. }
  140. if (count($backends) === 0) {
  141. return null;
  142. }
  143. /** @var GroupInterface[] $backends */
  144. $this->cachedGroups[$gid] = new Group($gid, $backends, $this->dispatcher, $this->userManager, $this, $displayName);
  145. return $this->cachedGroups[$gid];
  146. }
  147. /**
  148. * @brief Batch method to create group objects
  149. *
  150. * @param list<string> $gids List of groupIds for which we want to create a IGroup object
  151. * @param array<string, string> $displayNames Array containing already know display name for a groupId
  152. * @return array<string, IGroup>
  153. */
  154. protected function getGroupsObjects(array $gids, array $displayNames = []): array {
  155. $backends = [];
  156. $groups = [];
  157. foreach ($gids as $gid) {
  158. $backends[$gid] = [];
  159. if (!isset($displayNames[$gid])) {
  160. $displayNames[$gid] = null;
  161. }
  162. }
  163. foreach ($this->backends as $backend) {
  164. if ($backend instanceof IGroupDetailsBackend || $backend->implementsActions(GroupInterface::GROUP_DETAILS)) {
  165. /** @var IGroupDetailsBackend $backend */
  166. if ($backend instanceof IBatchMethodsBackend) {
  167. $groupDatas = $backend->getGroupsDetails($gids);
  168. } else {
  169. $groupDatas = [];
  170. foreach ($gids as $gid) {
  171. $groupDatas[$gid] = $backend->getGroupDetails($gid);
  172. }
  173. }
  174. foreach ($groupDatas as $gid => $groupData) {
  175. if (!empty($groupData)) {
  176. // take the display name from the last backend that has a non-null one
  177. if (isset($groupData['displayName'])) {
  178. $displayNames[$gid] = $groupData['displayName'];
  179. }
  180. $backends[$gid][] = $backend;
  181. }
  182. }
  183. } else {
  184. if ($backend instanceof IBatchMethodsBackend) {
  185. $existingGroups = $backend->groupsExists($gids);
  186. } else {
  187. $existingGroups = array_filter($gids, fn (string $gid): bool => $backend->groupExists($gid));
  188. }
  189. foreach ($existingGroups as $group) {
  190. $backends[$group][] = $backend;
  191. }
  192. }
  193. }
  194. foreach ($gids as $gid) {
  195. if (count($backends[$gid]) === 0) {
  196. continue;
  197. }
  198. $this->cachedGroups[$gid] = new Group($gid, $backends[$gid], $this->dispatcher, $this->userManager, $this, $displayNames[$gid]);
  199. $groups[$gid] = $this->cachedGroups[$gid];
  200. }
  201. return $groups;
  202. }
  203. /**
  204. * @param string $gid
  205. * @return bool
  206. */
  207. public function groupExists($gid) {
  208. return $this->get($gid) instanceof IGroup;
  209. }
  210. /**
  211. * @param string $gid
  212. * @return IGroup|null
  213. */
  214. public function createGroup($gid) {
  215. if ($gid === '' || $gid === null) {
  216. return null;
  217. } elseif ($group = $this->get($gid)) {
  218. return $group;
  219. } elseif (mb_strlen($gid) > self::MAX_GROUP_LENGTH) {
  220. throw new \Exception('Group name is limited to '. self::MAX_GROUP_LENGTH.' characters');
  221. } else {
  222. $this->dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
  223. $this->emit('\OC\Group', 'preCreate', [$gid]);
  224. foreach ($this->backends as $backend) {
  225. if ($backend->implementsActions(Backend::CREATE_GROUP)) {
  226. if ($backend instanceof ICreateNamedGroupBackend) {
  227. $groupName = $gid;
  228. if (($gid = $backend->createGroup($groupName)) !== null) {
  229. $group = $this->getGroupObject($gid);
  230. $this->dispatcher->dispatchTyped(new GroupCreatedEvent($group));
  231. $this->emit('\OC\Group', 'postCreate', [$group]);
  232. return $group;
  233. }
  234. } elseif ($backend->createGroup($gid)) {
  235. $group = $this->getGroupObject($gid);
  236. $this->dispatcher->dispatchTyped(new GroupCreatedEvent($group));
  237. $this->emit('\OC\Group', 'postCreate', [$group]);
  238. return $group;
  239. }
  240. }
  241. }
  242. return null;
  243. }
  244. }
  245. /**
  246. * @param string $search
  247. * @param ?int $limit
  248. * @param ?int $offset
  249. * @return \OC\Group\Group[]
  250. */
  251. public function search(string $search, ?int $limit = null, ?int $offset = 0) {
  252. $groups = [];
  253. foreach ($this->backends as $backend) {
  254. $groupIds = $backend->getGroups($search, $limit ?? -1, $offset ?? 0);
  255. $newGroups = $this->getGroupsObjects($groupIds);
  256. foreach ($newGroups as $groupId => $group) {
  257. $groups[$groupId] = $group;
  258. }
  259. if (!is_null($limit) and $limit <= 0) {
  260. return array_values($groups);
  261. }
  262. }
  263. return array_values($groups);
  264. }
  265. /**
  266. * @param IUser|null $user
  267. * @return \OC\Group\Group[]
  268. */
  269. public function getUserGroups(?IUser $user = null) {
  270. if (!$user instanceof IUser) {
  271. return [];
  272. }
  273. return $this->getUserIdGroups($user->getUID());
  274. }
  275. /**
  276. * @param string $uid the user id
  277. * @return \OC\Group\Group[]
  278. */
  279. public function getUserIdGroups(string $uid): array {
  280. $groups = [];
  281. foreach ($this->getUserIdGroupIds($uid) as $groupId) {
  282. $aGroup = $this->get($groupId);
  283. if ($aGroup instanceof IGroup) {
  284. $groups[$groupId] = $aGroup;
  285. } else {
  286. $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
  287. }
  288. }
  289. return $groups;
  290. }
  291. /**
  292. * Checks if a userId is in the admin group
  293. *
  294. * @param string $userId
  295. * @return bool if admin
  296. */
  297. public function isAdmin($userId) {
  298. foreach ($this->backends as $backend) {
  299. if (is_string($userId) && $backend->implementsActions(Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
  300. return true;
  301. }
  302. }
  303. return $this->isInGroup($userId, 'admin');
  304. }
  305. /**
  306. * Checks if a userId is in a group
  307. *
  308. * @param string $userId
  309. * @param string $group
  310. * @return bool if in group
  311. */
  312. public function isInGroup($userId, $group) {
  313. return in_array($group, $this->getUserIdGroupIds($userId));
  314. }
  315. /**
  316. * get a list of group ids for a user
  317. *
  318. * @param IUser $user
  319. * @return string[] with group ids
  320. */
  321. public function getUserGroupIds(IUser $user): array {
  322. return $this->getUserIdGroupIds($user->getUID());
  323. }
  324. /**
  325. * @param string $uid the user id
  326. * @return string[]
  327. */
  328. private function getUserIdGroupIds(string $uid): array {
  329. if (!isset($this->cachedUserGroups[$uid])) {
  330. $groups = [];
  331. foreach ($this->backends as $backend) {
  332. if ($groupIds = $backend->getUserGroups($uid)) {
  333. $groups = array_merge($groups, $groupIds);
  334. }
  335. }
  336. $this->cachedUserGroups[$uid] = $groups;
  337. }
  338. return $this->cachedUserGroups[$uid];
  339. }
  340. /**
  341. * @param string $groupId
  342. * @return ?string
  343. */
  344. public function getDisplayName(string $groupId): ?string {
  345. return $this->displayNameCache->getDisplayName($groupId);
  346. }
  347. /**
  348. * get an array of groupid and displayName for a user
  349. *
  350. * @param IUser $user
  351. * @return array ['displayName' => displayname]
  352. */
  353. public function getUserGroupNames(IUser $user) {
  354. return array_map(function ($group) {
  355. return ['displayName' => $this->displayNameCache->getDisplayName($group->getGID())];
  356. }, $this->getUserGroups($user));
  357. }
  358. /**
  359. * get a list of all display names in a group
  360. *
  361. * @param string $gid
  362. * @param string $search
  363. * @param int $limit
  364. * @param int $offset
  365. * @return array an array of display names (value) and user ids (key)
  366. */
  367. public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
  368. $group = $this->get($gid);
  369. if (is_null($group)) {
  370. return [];
  371. }
  372. $search = trim($search);
  373. $groupUsers = [];
  374. if (!empty($search)) {
  375. // only user backends have the capability to do a complex search for users
  376. $searchOffset = 0;
  377. $searchLimit = $limit * 100;
  378. if ($limit === -1) {
  379. $searchLimit = 500;
  380. }
  381. do {
  382. $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
  383. foreach ($filteredUsers as $filteredUser) {
  384. if ($group->inGroup($filteredUser)) {
  385. $groupUsers[] = $filteredUser;
  386. }
  387. }
  388. $searchOffset += $searchLimit;
  389. } while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
  390. if ($limit === -1) {
  391. $groupUsers = array_slice($groupUsers, $offset);
  392. } else {
  393. $groupUsers = array_slice($groupUsers, $offset, $limit);
  394. }
  395. } else {
  396. $groupUsers = $group->searchUsers('', $limit, $offset);
  397. }
  398. $matchingUsers = [];
  399. foreach ($groupUsers as $groupUser) {
  400. $matchingUsers[(string) $groupUser->getUID()] = $groupUser->getDisplayName();
  401. }
  402. return $matchingUsers;
  403. }
  404. /**
  405. * @return \OC\SubAdmin
  406. */
  407. public function getSubAdmin() {
  408. if (!$this->subAdmin) {
  409. $this->subAdmin = new \OC\SubAdmin(
  410. $this->userManager,
  411. $this,
  412. \OC::$server->getDatabaseConnection(),
  413. $this->dispatcher
  414. );
  415. }
  416. return $this->subAdmin;
  417. }
  418. }