1
0

Manager.php 13 KB

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