1
0

Manager.php 13 KB

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