Manager.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author John Molakvoæ <skjnldsv@protonmail.com>
  11. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  12. * @author Knut Ahlers <knut@ahlers.me>
  13. * @author Lukas Reschke <lukas@statuscode.ch>
  14. * @author macjohnny <estebanmarin@gmx.ch>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Robin Appelman <robin@icewind.nl>
  17. * @author Robin McCorkell <robin@mccorkell.me.uk>
  18. * @author Roeland Jago Douma <roeland@famdouma.nl>
  19. * @author Roman Kreisel <mail@romankreisel.de>
  20. * @author Thomas Müller <thomas.mueller@tmit.eu>
  21. * @author Vincent Petry <vincent@nextcloud.com>
  22. * @author Vinicius Cubas Brand <vinicius@eita.org.br>
  23. * @author voxsim "Simon Vocella"
  24. * @author Carl Schwan <carl@carlschwan.eu>
  25. *
  26. * @license AGPL-3.0
  27. *
  28. * This code is free software: you can redistribute it and/or modify
  29. * it under the terms of the GNU Affero General Public License, version 3,
  30. * as published by the Free Software Foundation.
  31. *
  32. * This program is distributed in the hope that it will be useful,
  33. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  35. * GNU Affero General Public License for more details.
  36. *
  37. * You should have received a copy of the GNU Affero General Public License, version 3,
  38. * along with this program. If not, see <http://www.gnu.org/licenses/>
  39. *
  40. */
  41. namespace OC\Group;
  42. use OC\Hooks\PublicEmitter;
  43. use OCP\EventDispatcher\IEventDispatcher;
  44. use OCP\Group\Backend\IBatchMethodsBackend;
  45. use OCP\Group\Backend\ICreateNamedGroupBackend;
  46. use OCP\Group\Backend\IGroupDetailsBackend;
  47. use OCP\Group\Events\BeforeGroupCreatedEvent;
  48. use OCP\Group\Events\GroupCreatedEvent;
  49. use OCP\GroupInterface;
  50. use OCP\ICacheFactory;
  51. use OCP\IGroup;
  52. use OCP\IGroupManager;
  53. use OCP\IUser;
  54. use Psr\Log\LoggerInterface;
  55. use function is_string;
  56. /**
  57. * Class Manager
  58. *
  59. * Hooks available in scope \OC\Group:
  60. * - preAddUser(\OC\Group\Group $group, \OC\User\User $user)
  61. * - postAddUser(\OC\Group\Group $group, \OC\User\User $user)
  62. * - preRemoveUser(\OC\Group\Group $group, \OC\User\User $user)
  63. * - postRemoveUser(\OC\Group\Group $group, \OC\User\User $user)
  64. * - preDelete(\OC\Group\Group $group)
  65. * - postDelete(\OC\Group\Group $group)
  66. * - preCreate(string $groupId)
  67. * - postCreate(\OC\Group\Group $group)
  68. *
  69. * @package OC\Group
  70. */
  71. class Manager extends PublicEmitter implements IGroupManager {
  72. /** @var GroupInterface[] */
  73. private $backends = [];
  74. /** @var \OC\User\Manager */
  75. private $userManager;
  76. private IEventDispatcher $dispatcher;
  77. private LoggerInterface $logger;
  78. /** @var array<string, IGroup> */
  79. private $cachedGroups = [];
  80. /** @var array<string, list<string>> */
  81. private $cachedUserGroups = [];
  82. /** @var \OC\SubAdmin */
  83. private $subAdmin = null;
  84. private DisplayNameCache $displayNameCache;
  85. private const MAX_GROUP_LENGTH = 255;
  86. public function __construct(\OC\User\Manager $userManager,
  87. IEventDispatcher $dispatcher,
  88. LoggerInterface $logger,
  89. ICacheFactory $cacheFactory) {
  90. $this->userManager = $userManager;
  91. $this->dispatcher = $dispatcher;
  92. $this->logger = $logger;
  93. $this->displayNameCache = new DisplayNameCache($cacheFactory, $this);
  94. $cachedGroups = &$this->cachedGroups;
  95. $cachedUserGroups = &$this->cachedUserGroups;
  96. $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
  97. /**
  98. * @var \OC\Group\Group $group
  99. */
  100. unset($cachedGroups[$group->getGID()]);
  101. $cachedUserGroups = [];
  102. });
  103. $this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
  104. /**
  105. * @var \OC\Group\Group $group
  106. */
  107. $cachedUserGroups = [];
  108. });
  109. $this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
  110. /**
  111. * @var \OC\Group\Group $group
  112. */
  113. $cachedUserGroups = [];
  114. });
  115. }
  116. /**
  117. * Checks whether a given backend is used
  118. *
  119. * @param string $backendClass Full classname including complete namespace
  120. * @return bool
  121. */
  122. public function isBackendUsed($backendClass) {
  123. $backendClass = strtolower(ltrim($backendClass, '\\'));
  124. foreach ($this->backends as $backend) {
  125. if (strtolower(get_class($backend)) === $backendClass) {
  126. return true;
  127. }
  128. }
  129. return false;
  130. }
  131. /**
  132. * @param \OCP\GroupInterface $backend
  133. */
  134. public function addBackend($backend) {
  135. $this->backends[] = $backend;
  136. $this->clearCaches();
  137. }
  138. public function clearBackends() {
  139. $this->backends = [];
  140. $this->clearCaches();
  141. }
  142. /**
  143. * Get the active backends
  144. *
  145. * @return \OCP\GroupInterface[]
  146. */
  147. public function getBackends() {
  148. return $this->backends;
  149. }
  150. protected function clearCaches() {
  151. $this->cachedGroups = [];
  152. $this->cachedUserGroups = [];
  153. }
  154. /**
  155. * @param string $gid
  156. * @return IGroup|null
  157. */
  158. public function get($gid) {
  159. if (isset($this->cachedGroups[$gid])) {
  160. return $this->cachedGroups[$gid];
  161. }
  162. return $this->getGroupObject($gid);
  163. }
  164. /**
  165. * @param string $gid
  166. * @param string $displayName
  167. * @return \OCP\IGroup|null
  168. */
  169. protected function getGroupObject($gid, $displayName = null) {
  170. $backends = [];
  171. foreach ($this->backends as $backend) {
  172. if ($backend->implementsActions(Backend::GROUP_DETAILS)) {
  173. $groupData = $backend->getGroupDetails($gid);
  174. if (is_array($groupData) && !empty($groupData)) {
  175. // take the display name from the last backend that has a non-null one
  176. if (is_null($displayName) && isset($groupData['displayName'])) {
  177. $displayName = $groupData['displayName'];
  178. }
  179. $backends[] = $backend;
  180. }
  181. } elseif ($backend->groupExists($gid)) {
  182. $backends[] = $backend;
  183. }
  184. }
  185. if (count($backends) === 0) {
  186. return null;
  187. }
  188. /** @var GroupInterface[] $backends */
  189. $this->cachedGroups[$gid] = new Group($gid, $backends, $this->dispatcher, $this->userManager, $this, $displayName);
  190. return $this->cachedGroups[$gid];
  191. }
  192. /**
  193. * @brief Batch method to create group objects
  194. *
  195. * @param list<string> $gids List of groupIds for which we want to create a IGroup object
  196. * @param array<string, string> $displayNames Array containing already know display name for a groupId
  197. * @return array<string, IGroup>
  198. */
  199. protected function getGroupsObjects(array $gids, array $displayNames = []): array {
  200. $backends = [];
  201. $groups = [];
  202. foreach ($gids as $gid) {
  203. $backends[$gid] = [];
  204. if (!isset($displayNames[$gid])) {
  205. $displayNames[$gid] = null;
  206. }
  207. }
  208. foreach ($this->backends as $backend) {
  209. if ($backend instanceof IGroupDetailsBackend || $backend->implementsActions(GroupInterface::GROUP_DETAILS)) {
  210. /** @var IGroupDetailsBackend $backend */
  211. if ($backend instanceof IBatchMethodsBackend) {
  212. $groupDatas = $backend->getGroupsDetails($gids);
  213. } else {
  214. $groupDatas = [];
  215. foreach ($gids as $gid) {
  216. $groupDatas[$gid] = $backend->getGroupDetails($gid);
  217. }
  218. }
  219. foreach ($groupDatas as $gid => $groupData) {
  220. if (!empty($groupData)) {
  221. // take the display name from the last backend that has a non-null one
  222. if (isset($groupData['displayName'])) {
  223. $displayNames[$gid] = $groupData['displayName'];
  224. }
  225. $backends[$gid][] = $backend;
  226. }
  227. }
  228. } else {
  229. if ($backend instanceof IBatchMethodsBackend) {
  230. $existingGroups = $backend->groupsExists($gids);
  231. } else {
  232. $existingGroups = array_filter($gids, fn (string $gid): bool => $backend->groupExists($gid));
  233. }
  234. foreach ($existingGroups as $group) {
  235. $backends[$group][] = $backend;
  236. }
  237. }
  238. }
  239. foreach ($gids as $gid) {
  240. if (count($backends[$gid]) === 0) {
  241. continue;
  242. }
  243. $this->cachedGroups[$gid] = new Group($gid, $backends[$gid], $this->dispatcher, $this->userManager, $this, $displayNames[$gid]);
  244. $groups[$gid] = $this->cachedGroups[$gid];
  245. }
  246. return $groups;
  247. }
  248. /**
  249. * @param string $gid
  250. * @return bool
  251. */
  252. public function groupExists($gid) {
  253. return $this->get($gid) instanceof IGroup;
  254. }
  255. /**
  256. * @param string $gid
  257. * @return IGroup|null
  258. */
  259. public function createGroup($gid) {
  260. if ($gid === '' || $gid === null) {
  261. return null;
  262. } elseif ($group = $this->get($gid)) {
  263. return $group;
  264. } elseif (mb_strlen($gid) > self::MAX_GROUP_LENGTH) {
  265. throw new \Exception('Group name is limited to '. self::MAX_GROUP_LENGTH.' characters');
  266. } else {
  267. $this->dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
  268. $this->emit('\OC\Group', 'preCreate', [$gid]);
  269. foreach ($this->backends as $backend) {
  270. if ($backend->implementsActions(Backend::CREATE_GROUP)) {
  271. if ($backend instanceof ICreateNamedGroupBackend) {
  272. $groupName = $gid;
  273. if (($gid = $backend->createGroup($groupName)) !== null) {
  274. $group = $this->getGroupObject($gid);
  275. $this->dispatcher->dispatchTyped(new GroupCreatedEvent($group));
  276. $this->emit('\OC\Group', 'postCreate', [$group]);
  277. return $group;
  278. }
  279. } elseif ($backend->createGroup($gid)) {
  280. $group = $this->getGroupObject($gid);
  281. $this->dispatcher->dispatchTyped(new GroupCreatedEvent($group));
  282. $this->emit('\OC\Group', 'postCreate', [$group]);
  283. return $group;
  284. }
  285. }
  286. }
  287. return null;
  288. }
  289. }
  290. /**
  291. * @param string $search
  292. * @param ?int $limit
  293. * @param ?int $offset
  294. * @return \OC\Group\Group[]
  295. */
  296. public function search(string $search, ?int $limit = null, ?int $offset = 0) {
  297. $groups = [];
  298. foreach ($this->backends as $backend) {
  299. $groupIds = $backend->getGroups($search, $limit ?? -1, $offset ?? 0);
  300. $newGroups = $this->getGroupsObjects($groupIds);
  301. foreach ($newGroups as $groupId => $group) {
  302. $groups[$groupId] = $group;
  303. }
  304. if (!is_null($limit) and $limit <= 0) {
  305. return array_values($groups);
  306. }
  307. }
  308. return array_values($groups);
  309. }
  310. /**
  311. * @param IUser|null $user
  312. * @return \OC\Group\Group[]
  313. */
  314. public function getUserGroups(?IUser $user = null) {
  315. if (!$user instanceof IUser) {
  316. return [];
  317. }
  318. return $this->getUserIdGroups($user->getUID());
  319. }
  320. /**
  321. * @param string $uid the user id
  322. * @return \OC\Group\Group[]
  323. */
  324. public function getUserIdGroups(string $uid): array {
  325. $groups = [];
  326. foreach ($this->getUserIdGroupIds($uid) as $groupId) {
  327. $aGroup = $this->get($groupId);
  328. if ($aGroup instanceof IGroup) {
  329. $groups[$groupId] = $aGroup;
  330. } else {
  331. $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
  332. }
  333. }
  334. return $groups;
  335. }
  336. /**
  337. * Checks if a userId is in the admin group
  338. *
  339. * @param string $userId
  340. * @return bool if admin
  341. */
  342. public function isAdmin($userId) {
  343. foreach ($this->backends as $backend) {
  344. if (is_string($userId) && $backend->implementsActions(Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
  345. return true;
  346. }
  347. }
  348. return $this->isInGroup($userId, 'admin');
  349. }
  350. /**
  351. * Checks if a userId is in a group
  352. *
  353. * @param string $userId
  354. * @param string $group
  355. * @return bool if in group
  356. */
  357. public function isInGroup($userId, $group) {
  358. return in_array($group, $this->getUserIdGroupIds($userId));
  359. }
  360. /**
  361. * get a list of group ids for a user
  362. *
  363. * @param IUser $user
  364. * @return string[] with group ids
  365. */
  366. public function getUserGroupIds(IUser $user): array {
  367. return $this->getUserIdGroupIds($user->getUID());
  368. }
  369. /**
  370. * @param string $uid the user id
  371. * @return string[]
  372. */
  373. private function getUserIdGroupIds(string $uid): array {
  374. if (!isset($this->cachedUserGroups[$uid])) {
  375. $groups = [];
  376. foreach ($this->backends as $backend) {
  377. if ($groupIds = $backend->getUserGroups($uid)) {
  378. $groups = array_merge($groups, $groupIds);
  379. }
  380. }
  381. $this->cachedUserGroups[$uid] = $groups;
  382. }
  383. return $this->cachedUserGroups[$uid];
  384. }
  385. /**
  386. * @param string $groupId
  387. * @return ?string
  388. */
  389. public function getDisplayName(string $groupId): ?string {
  390. return $this->displayNameCache->getDisplayName($groupId);
  391. }
  392. /**
  393. * get an array of groupid and displayName for a user
  394. *
  395. * @param IUser $user
  396. * @return array ['displayName' => displayname]
  397. */
  398. public function getUserGroupNames(IUser $user) {
  399. return array_map(function ($group) {
  400. return ['displayName' => $this->displayNameCache->getDisplayName($group->getGID())];
  401. }, $this->getUserGroups($user));
  402. }
  403. /**
  404. * get a list of all display names in a group
  405. *
  406. * @param string $gid
  407. * @param string $search
  408. * @param int $limit
  409. * @param int $offset
  410. * @return array an array of display names (value) and user ids (key)
  411. */
  412. public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
  413. $group = $this->get($gid);
  414. if (is_null($group)) {
  415. return [];
  416. }
  417. $search = trim($search);
  418. $groupUsers = [];
  419. if (!empty($search)) {
  420. // only user backends have the capability to do a complex search for users
  421. $searchOffset = 0;
  422. $searchLimit = $limit * 100;
  423. if ($limit === -1) {
  424. $searchLimit = 500;
  425. }
  426. do {
  427. $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
  428. foreach ($filteredUsers as $filteredUser) {
  429. if ($group->inGroup($filteredUser)) {
  430. $groupUsers[] = $filteredUser;
  431. }
  432. }
  433. $searchOffset += $searchLimit;
  434. } while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
  435. if ($limit === -1) {
  436. $groupUsers = array_slice($groupUsers, $offset);
  437. } else {
  438. $groupUsers = array_slice($groupUsers, $offset, $limit);
  439. }
  440. } else {
  441. $groupUsers = $group->searchUsers('', $limit, $offset);
  442. }
  443. $matchingUsers = [];
  444. foreach ($groupUsers as $groupUser) {
  445. $matchingUsers[(string) $groupUser->getUID()] = $groupUser->getDisplayName();
  446. }
  447. return $matchingUsers;
  448. }
  449. /**
  450. * @return \OC\SubAdmin
  451. */
  452. public function getSubAdmin() {
  453. if (!$this->subAdmin) {
  454. $this->subAdmin = new \OC\SubAdmin(
  455. $this->userManager,
  456. $this,
  457. \OC::$server->getDatabaseConnection(),
  458. $this->dispatcher
  459. );
  460. }
  461. return $this->subAdmin;
  462. }
  463. }