Manager.php 13 KB

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