Manager.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. $this->listen('\OC\Group', 'postDelete', function (IGroup $group): void {
  95. unset($this->cachedGroups[$group->getGID()]);
  96. $this->cachedUserGroups = [];
  97. });
  98. $this->listen('\OC\Group', 'postAddUser', function (IGroup $group): void {
  99. $this->cachedUserGroups = [];
  100. });
  101. $this->listen('\OC\Group', 'postRemoveUser', function (IGroup $group): void {
  102. $this->cachedUserGroups = [];
  103. });
  104. }
  105. /**
  106. * Checks whether a given backend is used
  107. *
  108. * @param string $backendClass Full classname including complete namespace
  109. * @return bool
  110. */
  111. public function isBackendUsed($backendClass) {
  112. $backendClass = strtolower(ltrim($backendClass, '\\'));
  113. foreach ($this->backends as $backend) {
  114. if (strtolower(get_class($backend)) === $backendClass) {
  115. return true;
  116. }
  117. }
  118. return false;
  119. }
  120. /**
  121. * @param \OCP\GroupInterface $backend
  122. */
  123. public function addBackend($backend) {
  124. $this->backends[] = $backend;
  125. $this->clearCaches();
  126. }
  127. public function clearBackends() {
  128. $this->backends = [];
  129. $this->clearCaches();
  130. }
  131. /**
  132. * Get the active backends
  133. *
  134. * @return \OCP\GroupInterface[]
  135. */
  136. public function getBackends() {
  137. return $this->backends;
  138. }
  139. protected function clearCaches() {
  140. $this->cachedGroups = [];
  141. $this->cachedUserGroups = [];
  142. }
  143. /**
  144. * @param string $gid
  145. * @return IGroup|null
  146. */
  147. public function get($gid) {
  148. if (isset($this->cachedGroups[$gid])) {
  149. return $this->cachedGroups[$gid];
  150. }
  151. return $this->getGroupObject($gid);
  152. }
  153. /**
  154. * @param string $gid
  155. * @param string $displayName
  156. * @return \OCP\IGroup|null
  157. */
  158. protected function getGroupObject($gid, $displayName = null) {
  159. $backends = [];
  160. foreach ($this->backends as $backend) {
  161. if ($backend->implementsActions(Backend::GROUP_DETAILS)) {
  162. $groupData = $backend->getGroupDetails($gid);
  163. if (is_array($groupData) && !empty($groupData)) {
  164. // take the display name from the last backend that has a non-null one
  165. if (is_null($displayName) && isset($groupData['displayName'])) {
  166. $displayName = $groupData['displayName'];
  167. }
  168. $backends[] = $backend;
  169. }
  170. } elseif ($backend->groupExists($gid)) {
  171. $backends[] = $backend;
  172. }
  173. }
  174. if (count($backends) === 0) {
  175. return null;
  176. }
  177. /** @var GroupInterface[] $backends */
  178. $this->cachedGroups[$gid] = new Group($gid, $backends, $this->dispatcher, $this->userManager, $this, $displayName);
  179. return $this->cachedGroups[$gid];
  180. }
  181. /**
  182. * @brief Batch method to create group objects
  183. *
  184. * @param list<string> $gids List of groupIds for which we want to create a IGroup object
  185. * @param array<string, string> $displayNames Array containing already know display name for a groupId
  186. * @return array<string, IGroup>
  187. */
  188. protected function getGroupsObjects(array $gids, array $displayNames = []): array {
  189. $backends = [];
  190. $groups = [];
  191. foreach ($gids as $gid) {
  192. $backends[$gid] = [];
  193. if (!isset($displayNames[$gid])) {
  194. $displayNames[$gid] = null;
  195. }
  196. }
  197. foreach ($this->backends as $backend) {
  198. if ($backend instanceof IGroupDetailsBackend || $backend->implementsActions(GroupInterface::GROUP_DETAILS)) {
  199. /** @var IGroupDetailsBackend $backend */
  200. if ($backend instanceof IBatchMethodsBackend) {
  201. $groupDatas = $backend->getGroupsDetails($gids);
  202. } else {
  203. $groupDatas = [];
  204. foreach ($gids as $gid) {
  205. $groupDatas[$gid] = $backend->getGroupDetails($gid);
  206. }
  207. }
  208. foreach ($groupDatas as $gid => $groupData) {
  209. if (!empty($groupData)) {
  210. // take the display name from the last backend that has a non-null one
  211. if (isset($groupData['displayName'])) {
  212. $displayNames[$gid] = $groupData['displayName'];
  213. }
  214. $backends[$gid][] = $backend;
  215. }
  216. }
  217. } else {
  218. if ($backend instanceof IBatchMethodsBackend) {
  219. $existingGroups = $backend->groupsExists($gids);
  220. } else {
  221. $existingGroups = array_filter($gids, fn (string $gid): bool => $backend->groupExists($gid));
  222. }
  223. foreach ($existingGroups as $group) {
  224. $backends[$group][] = $backend;
  225. }
  226. }
  227. }
  228. foreach ($gids as $gid) {
  229. if (count($backends[$gid]) === 0) {
  230. continue;
  231. }
  232. $this->cachedGroups[$gid] = new Group($gid, $backends[$gid], $this->dispatcher, $this->userManager, $this, $displayNames[$gid]);
  233. $groups[$gid] = $this->cachedGroups[$gid];
  234. }
  235. return $groups;
  236. }
  237. /**
  238. * @param string $gid
  239. * @return bool
  240. */
  241. public function groupExists($gid) {
  242. return $this->get($gid) instanceof IGroup;
  243. }
  244. /**
  245. * @param string $gid
  246. * @return IGroup|null
  247. */
  248. public function createGroup($gid) {
  249. if ($gid === '' || $gid === null) {
  250. return null;
  251. } elseif ($group = $this->get($gid)) {
  252. return $group;
  253. } elseif (mb_strlen($gid) > self::MAX_GROUP_LENGTH) {
  254. throw new \Exception('Group name is limited to '. self::MAX_GROUP_LENGTH.' characters');
  255. } else {
  256. $this->dispatcher->dispatchTyped(new BeforeGroupCreatedEvent($gid));
  257. $this->emit('\OC\Group', 'preCreate', [$gid]);
  258. foreach ($this->backends as $backend) {
  259. if ($backend->implementsActions(Backend::CREATE_GROUP)) {
  260. if ($backend instanceof ICreateNamedGroupBackend) {
  261. $groupName = $gid;
  262. if (($gid = $backend->createGroup($groupName)) !== null) {
  263. $group = $this->getGroupObject($gid);
  264. $this->dispatcher->dispatchTyped(new GroupCreatedEvent($group));
  265. $this->emit('\OC\Group', 'postCreate', [$group]);
  266. return $group;
  267. }
  268. } elseif ($backend->createGroup($gid)) {
  269. $group = $this->getGroupObject($gid);
  270. $this->dispatcher->dispatchTyped(new GroupCreatedEvent($group));
  271. $this->emit('\OC\Group', 'postCreate', [$group]);
  272. return $group;
  273. }
  274. }
  275. }
  276. return null;
  277. }
  278. }
  279. /**
  280. * @param string $search
  281. * @param ?int $limit
  282. * @param ?int $offset
  283. * @return \OC\Group\Group[]
  284. */
  285. public function search(string $search, ?int $limit = null, ?int $offset = 0) {
  286. $groups = [];
  287. foreach ($this->backends as $backend) {
  288. $groupIds = $backend->getGroups($search, $limit ?? -1, $offset ?? 0);
  289. $newGroups = $this->getGroupsObjects($groupIds);
  290. foreach ($newGroups as $groupId => $group) {
  291. $groups[$groupId] = $group;
  292. }
  293. if (!is_null($limit) and $limit <= 0) {
  294. return array_values($groups);
  295. }
  296. }
  297. return array_values($groups);
  298. }
  299. /**
  300. * @param IUser|null $user
  301. * @return \OC\Group\Group[]
  302. */
  303. public function getUserGroups(?IUser $user = null) {
  304. if (!$user instanceof IUser) {
  305. return [];
  306. }
  307. return $this->getUserIdGroups($user->getUID());
  308. }
  309. /**
  310. * @param string $uid the user id
  311. * @return \OC\Group\Group[]
  312. */
  313. public function getUserIdGroups(string $uid): array {
  314. $groups = [];
  315. foreach ($this->getUserIdGroupIds($uid) as $groupId) {
  316. $aGroup = $this->get($groupId);
  317. if ($aGroup instanceof IGroup) {
  318. $groups[$groupId] = $aGroup;
  319. } else {
  320. $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
  321. }
  322. }
  323. return $groups;
  324. }
  325. /**
  326. * Checks if a userId is in the admin group
  327. *
  328. * @param string $userId
  329. * @return bool if admin
  330. */
  331. public function isAdmin($userId) {
  332. foreach ($this->backends as $backend) {
  333. if (is_string($userId) && $backend->implementsActions(Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
  334. return true;
  335. }
  336. }
  337. return $this->isInGroup($userId, 'admin');
  338. }
  339. /**
  340. * Checks if a userId is in a group
  341. *
  342. * @param string $userId
  343. * @param string $group
  344. * @return bool if in group
  345. */
  346. public function isInGroup($userId, $group) {
  347. return in_array($group, $this->getUserIdGroupIds($userId));
  348. }
  349. /**
  350. * get a list of group ids for a user
  351. *
  352. * @param IUser $user
  353. * @return string[] with group ids
  354. */
  355. public function getUserGroupIds(IUser $user): array {
  356. return $this->getUserIdGroupIds($user->getUID());
  357. }
  358. /**
  359. * @param string $uid the user id
  360. * @return string[]
  361. */
  362. private function getUserIdGroupIds(string $uid): array {
  363. if (!isset($this->cachedUserGroups[$uid])) {
  364. $groups = [];
  365. foreach ($this->backends as $backend) {
  366. if ($groupIds = $backend->getUserGroups($uid)) {
  367. $groups = array_merge($groups, $groupIds);
  368. }
  369. }
  370. $this->cachedUserGroups[$uid] = $groups;
  371. }
  372. return $this->cachedUserGroups[$uid];
  373. }
  374. /**
  375. * @param string $groupId
  376. * @return ?string
  377. */
  378. public function getDisplayName(string $groupId): ?string {
  379. return $this->displayNameCache->getDisplayName($groupId);
  380. }
  381. /**
  382. * get an array of groupid and displayName for a user
  383. *
  384. * @param IUser $user
  385. * @return array ['displayName' => displayname]
  386. */
  387. public function getUserGroupNames(IUser $user) {
  388. return array_map(function ($group) {
  389. return ['displayName' => $this->displayNameCache->getDisplayName($group->getGID())];
  390. }, $this->getUserGroups($user));
  391. }
  392. /**
  393. * get a list of all display names in a group
  394. *
  395. * @param string $gid
  396. * @param string $search
  397. * @param int $limit
  398. * @param int $offset
  399. * @return array an array of display names (value) and user ids (key)
  400. */
  401. public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
  402. $group = $this->get($gid);
  403. if (is_null($group)) {
  404. return [];
  405. }
  406. $search = trim($search);
  407. $groupUsers = [];
  408. if (!empty($search)) {
  409. // only user backends have the capability to do a complex search for users
  410. $searchOffset = 0;
  411. $searchLimit = $limit * 100;
  412. if ($limit === -1) {
  413. $searchLimit = 500;
  414. }
  415. do {
  416. $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
  417. foreach ($filteredUsers as $filteredUser) {
  418. if ($group->inGroup($filteredUser)) {
  419. $groupUsers[] = $filteredUser;
  420. }
  421. }
  422. $searchOffset += $searchLimit;
  423. } while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
  424. if ($limit === -1) {
  425. $groupUsers = array_slice($groupUsers, $offset);
  426. } else {
  427. $groupUsers = array_slice($groupUsers, $offset, $limit);
  428. }
  429. } else {
  430. $groupUsers = $group->searchUsers('', $limit, $offset);
  431. }
  432. $matchingUsers = [];
  433. foreach ($groupUsers as $groupUser) {
  434. $matchingUsers[(string) $groupUser->getUID()] = $groupUser->getDisplayName();
  435. }
  436. return $matchingUsers;
  437. }
  438. /**
  439. * @return \OC\SubAdmin
  440. */
  441. public function getSubAdmin() {
  442. if (!$this->subAdmin) {
  443. $this->subAdmin = new \OC\SubAdmin(
  444. $this->userManager,
  445. $this,
  446. \OC::$server->getDatabaseConnection(),
  447. $this->dispatcher
  448. );
  449. }
  450. return $this->subAdmin;
  451. }
  452. }