Manager.php 13 KB

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