Manager.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. *
  25. * @license AGPL-3.0
  26. *
  27. * This code is free software: you can redistribute it and/or modify
  28. * it under the terms of the GNU Affero General Public License, version 3,
  29. * as published by the Free Software Foundation.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU Affero General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU Affero General Public License, version 3,
  37. * along with this program. If not, see <http://www.gnu.org/licenses/>
  38. *
  39. */
  40. namespace OC\Group;
  41. use OC\Hooks\PublicEmitter;
  42. use OCP\EventDispatcher\IEventDispatcher;
  43. use OCP\GroupInterface;
  44. use OCP\Group\Backend\ICreateNamedGroupBackend;
  45. use OCP\ICacheFactory;
  46. use OCP\IGroup;
  47. use OCP\IGroupManager;
  48. use OCP\IUser;
  49. use Psr\Log\LoggerInterface;
  50. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  51. /**
  52. * Class Manager
  53. *
  54. * Hooks available in scope \OC\Group:
  55. * - preAddUser(\OC\Group\Group $group, \OC\User\User $user)
  56. * - postAddUser(\OC\Group\Group $group, \OC\User\User $user)
  57. * - preRemoveUser(\OC\Group\Group $group, \OC\User\User $user)
  58. * - postRemoveUser(\OC\Group\Group $group, \OC\User\User $user)
  59. * - preDelete(\OC\Group\Group $group)
  60. * - postDelete(\OC\Group\Group $group)
  61. * - preCreate(string $groupId)
  62. * - postCreate(\OC\Group\Group $group)
  63. *
  64. * @package OC\Group
  65. */
  66. class Manager extends PublicEmitter implements IGroupManager {
  67. /** @var GroupInterface[] */
  68. private $backends = [];
  69. /** @var \OC\User\Manager */
  70. private $userManager;
  71. /** @var EventDispatcherInterface */
  72. private $dispatcher;
  73. private LoggerInterface $logger;
  74. /** @var \OC\Group\Group[] */
  75. private $cachedGroups = [];
  76. /** @var (string[])[] */
  77. private $cachedUserGroups = [];
  78. /** @var \OC\SubAdmin */
  79. private $subAdmin = null;
  80. private DisplayNameCache $displayNameCache;
  81. private const MAX_GROUP_LENGTH = 255;
  82. public function __construct(\OC\User\Manager $userManager,
  83. EventDispatcherInterface $dispatcher,
  84. LoggerInterface $logger,
  85. ICacheFactory $cacheFactory) {
  86. $this->userManager = $userManager;
  87. $this->dispatcher = $dispatcher;
  88. $this->logger = $logger;
  89. $this->displayNameCache = new DisplayNameCache($cacheFactory, $this);
  90. $cachedGroups = &$this->cachedGroups;
  91. $cachedUserGroups = &$this->cachedUserGroups;
  92. $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
  93. /**
  94. * @var \OC\Group\Group $group
  95. */
  96. unset($cachedGroups[$group->getGID()]);
  97. $cachedUserGroups = [];
  98. });
  99. $this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
  100. /**
  101. * @var \OC\Group\Group $group
  102. */
  103. $cachedUserGroups = [];
  104. });
  105. $this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
  106. /**
  107. * @var \OC\Group\Group $group
  108. */
  109. $cachedUserGroups = [];
  110. });
  111. }
  112. /**
  113. * Checks whether a given backend is used
  114. *
  115. * @param string $backendClass Full classname including complete namespace
  116. * @return bool
  117. */
  118. public function isBackendUsed($backendClass) {
  119. $backendClass = strtolower(ltrim($backendClass, '\\'));
  120. foreach ($this->backends as $backend) {
  121. if (strtolower(get_class($backend)) === $backendClass) {
  122. return true;
  123. }
  124. }
  125. return false;
  126. }
  127. /**
  128. * @param \OCP\GroupInterface $backend
  129. */
  130. public function addBackend($backend) {
  131. $this->backends[] = $backend;
  132. $this->clearCaches();
  133. }
  134. public function clearBackends() {
  135. $this->backends = [];
  136. $this->clearCaches();
  137. }
  138. /**
  139. * Get the active backends
  140. *
  141. * @return \OCP\GroupInterface[]
  142. */
  143. public function getBackends() {
  144. return $this->backends;
  145. }
  146. protected function clearCaches() {
  147. $this->cachedGroups = [];
  148. $this->cachedUserGroups = [];
  149. }
  150. /**
  151. * @param string $gid
  152. * @return IGroup|null
  153. */
  154. public function get($gid) {
  155. if (isset($this->cachedGroups[$gid])) {
  156. return $this->cachedGroups[$gid];
  157. }
  158. return $this->getGroupObject($gid);
  159. }
  160. /**
  161. * @param string $gid
  162. * @param string $displayName
  163. * @return \OCP\IGroup|null
  164. */
  165. protected function getGroupObject($gid, $displayName = null) {
  166. $backends = [];
  167. foreach ($this->backends as $backend) {
  168. if ($backend->implementsActions(Backend::GROUP_DETAILS)) {
  169. $groupData = $backend->getGroupDetails($gid);
  170. if (is_array($groupData) && !empty($groupData)) {
  171. // take the display name from the first backend that has a non-null one
  172. if (is_null($displayName) && isset($groupData['displayName'])) {
  173. $displayName = $groupData['displayName'];
  174. }
  175. $backends[] = $backend;
  176. }
  177. } elseif ($backend->groupExists($gid)) {
  178. $backends[] = $backend;
  179. }
  180. }
  181. if (count($backends) === 0) {
  182. return null;
  183. }
  184. $this->cachedGroups[$gid] = new Group($gid, $backends, $this->dispatcher, $this->userManager, $this, $displayName);
  185. return $this->cachedGroups[$gid];
  186. }
  187. /**
  188. * @param string $gid
  189. * @return bool
  190. */
  191. public function groupExists($gid) {
  192. return $this->get($gid) instanceof IGroup;
  193. }
  194. /**
  195. * @param string $gid
  196. * @return IGroup|null
  197. */
  198. public function createGroup($gid) {
  199. if ($gid === '' || $gid === null) {
  200. return null;
  201. } elseif ($group = $this->get($gid)) {
  202. return $group;
  203. } elseif (mb_strlen($gid) > self::MAX_GROUP_LENGTH) {
  204. throw new \Exception('Group name is limited to '. self::MAX_GROUP_LENGTH.' characters');
  205. } else {
  206. $this->emit('\OC\Group', 'preCreate', [$gid]);
  207. foreach ($this->backends as $backend) {
  208. if ($backend->implementsActions(Backend::CREATE_GROUP)) {
  209. if ($backend instanceof ICreateNamedGroupBackend) {
  210. $groupName = $gid;
  211. if (($gid = $backend->createGroup($groupName)) !== null) {
  212. $group = $this->getGroupObject($gid);
  213. $this->emit('\OC\Group', 'postCreate', [$group]);
  214. return $group;
  215. }
  216. } elseif ($backend->createGroup($gid)) {
  217. $group = $this->getGroupObject($gid);
  218. $this->emit('\OC\Group', 'postCreate', [$group]);
  219. return $group;
  220. }
  221. }
  222. }
  223. return null;
  224. }
  225. }
  226. /**
  227. * @param string $search
  228. * @param ?int $limit
  229. * @param ?int $offset
  230. * @return \OC\Group\Group[]
  231. */
  232. public function search(string $search, ?int $limit = null, ?int $offset = 0) {
  233. $groups = [];
  234. foreach ($this->backends as $backend) {
  235. $groupIds = $backend->getGroups($search, $limit ?? -1, $offset ?? 0);
  236. foreach ($groupIds as $groupId) {
  237. $aGroup = $this->get($groupId);
  238. if ($aGroup instanceof IGroup) {
  239. $groups[$groupId] = $aGroup;
  240. } else {
  241. $this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
  242. }
  243. }
  244. if (!is_null($limit) and $limit <= 0) {
  245. return array_values($groups);
  246. }
  247. }
  248. return array_values($groups);
  249. }
  250. /**
  251. * @param IUser|null $user
  252. * @return \OC\Group\Group[]
  253. */
  254. public function getUserGroups(IUser $user = null) {
  255. if (!$user instanceof IUser) {
  256. return [];
  257. }
  258. return $this->getUserIdGroups($user->getUID());
  259. }
  260. /**
  261. * @param string $uid the user id
  262. * @return \OC\Group\Group[]
  263. */
  264. public function getUserIdGroups(string $uid): array {
  265. $groups = [];
  266. foreach ($this->getUserIdGroupIds($uid) as $groupId) {
  267. $aGroup = $this->get($groupId);
  268. if ($aGroup instanceof IGroup) {
  269. $groups[$groupId] = $aGroup;
  270. } else {
  271. $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
  272. }
  273. }
  274. return $groups;
  275. }
  276. /**
  277. * Checks if a userId is in the admin group
  278. *
  279. * @param string $userId
  280. * @return bool if admin
  281. */
  282. public function isAdmin($userId) {
  283. foreach ($this->backends as $backend) {
  284. if ($backend->implementsActions(Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
  285. return true;
  286. }
  287. }
  288. return $this->isInGroup($userId, 'admin');
  289. }
  290. /**
  291. * Checks if a userId is in a group
  292. *
  293. * @param string $userId
  294. * @param string $group
  295. * @return bool if in group
  296. */
  297. public function isInGroup($userId, $group) {
  298. return array_search($group, $this->getUserIdGroupIds($userId)) !== false;
  299. }
  300. /**
  301. * get a list of group ids for a user
  302. *
  303. * @param IUser $user
  304. * @return string[] with group ids
  305. */
  306. public function getUserGroupIds(IUser $user): array {
  307. return $this->getUserIdGroupIds($user->getUID());
  308. }
  309. /**
  310. * @param string $uid the user id
  311. * @return string[]
  312. */
  313. private function getUserIdGroupIds(string $uid): array {
  314. if (!isset($this->cachedUserGroups[$uid])) {
  315. $groups = [];
  316. foreach ($this->backends as $backend) {
  317. if ($groupIds = $backend->getUserGroups($uid)) {
  318. $groups = array_merge($groups, $groupIds);
  319. }
  320. }
  321. $this->cachedUserGroups[$uid] = $groups;
  322. }
  323. return $this->cachedUserGroups[$uid];
  324. }
  325. /**
  326. * @param string $groupId
  327. * @return ?string
  328. */
  329. public function getDisplayName(string $groupId): ?string {
  330. return $this->displayNameCache->getDisplayName($groupId);
  331. }
  332. /**
  333. * get an array of groupid and displayName for a user
  334. *
  335. * @param IUser $user
  336. * @return array ['displayName' => displayname]
  337. */
  338. public function getUserGroupNames(IUser $user) {
  339. return array_map(function ($group) {
  340. return ['displayName' => $this->displayNameCache->getDisplayName($group->getGID())];
  341. }, $this->getUserGroups($user));
  342. }
  343. /**
  344. * get a list of all display names in a group
  345. *
  346. * @param string $gid
  347. * @param string $search
  348. * @param int $limit
  349. * @param int $offset
  350. * @return array an array of display names (value) and user ids (key)
  351. */
  352. public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
  353. $group = $this->get($gid);
  354. if (is_null($group)) {
  355. return [];
  356. }
  357. $search = trim($search);
  358. $groupUsers = [];
  359. if (!empty($search)) {
  360. // only user backends have the capability to do a complex search for users
  361. $searchOffset = 0;
  362. $searchLimit = $limit * 100;
  363. if ($limit === -1) {
  364. $searchLimit = 500;
  365. }
  366. do {
  367. $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
  368. foreach ($filteredUsers as $filteredUser) {
  369. if ($group->inGroup($filteredUser)) {
  370. $groupUsers[] = $filteredUser;
  371. }
  372. }
  373. $searchOffset += $searchLimit;
  374. } while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
  375. if ($limit === -1) {
  376. $groupUsers = array_slice($groupUsers, $offset);
  377. } else {
  378. $groupUsers = array_slice($groupUsers, $offset, $limit);
  379. }
  380. } else {
  381. $groupUsers = $group->searchUsers('', $limit, $offset);
  382. }
  383. $matchingUsers = [];
  384. foreach ($groupUsers as $groupUser) {
  385. $matchingUsers[(string) $groupUser->getUID()] = $groupUser->getDisplayName();
  386. }
  387. return $matchingUsers;
  388. }
  389. /**
  390. * @return \OC\SubAdmin
  391. */
  392. public function getSubAdmin() {
  393. if (!$this->subAdmin) {
  394. $this->subAdmin = new \OC\SubAdmin(
  395. $this->userManager,
  396. $this,
  397. \OC::$server->getDatabaseConnection(),
  398. \OC::$server->get(IEventDispatcher::class)
  399. );
  400. }
  401. return $this->subAdmin;
  402. }
  403. }