1
0

Manager.php 11 KB

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