Group_LDAP.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Alexander Bergolth <leo@strike.wu.ac.at>
  6. * @author Alex Weirig <alex.weirig@technolink.lu>
  7. * @author alexweirig <alex.weirig@technolink.lu>
  8. * @author Andreas Fischer <bantu@owncloud.com>
  9. * @author Andreas Pflug <dev@admin4.org>
  10. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  11. * @author Bart Visscher <bartv@thisnet.nl>
  12. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  13. * @author Clement Wong <git@clement.hk>
  14. * @author Frédéric Fortier <frederic.fortier@oronospolytechnique.com>
  15. * @author Joas Schilling <coding@schilljs.com>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Morris Jobke <hey@morrisjobke.de>
  18. * @author Nicolas Grekas <nicolas.grekas@gmail.com>
  19. * @author Robin McCorkell <robin@mccorkell.me.uk>
  20. * @author Roeland Jago Douma <roeland@famdouma.nl>
  21. * @author Roland Tapken <roland@bitarbeiter.net>
  22. * @author Thomas Müller <thomas.mueller@tmit.eu>
  23. * @author Tobias Perschon <tobias@perschon.at>
  24. * @author Victor Dubiniuk <dubiniuk@owncloud.com>
  25. * @author Vinicius Cubas Brand <vinicius@eita.org.br>
  26. * @author Xuanwo <xuanwo@yunify.com>
  27. * @author Carl Schwan <carl@carlschwan.eu>
  28. * @author Côme Chilliet <come.chilliet@nextcloud.com>
  29. *
  30. * @license AGPL-3.0
  31. *
  32. * This code is free software: you can redistribute it and/or modify
  33. * it under the terms of the GNU Affero General Public License, version 3,
  34. * as published by the Free Software Foundation.
  35. *
  36. * This program is distributed in the hope that it will be useful,
  37. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  38. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  39. * GNU Affero General Public License for more details.
  40. *
  41. * You should have received a copy of the GNU Affero General Public License, version 3,
  42. * along with this program. If not, see <http://www.gnu.org/licenses/>
  43. *
  44. */
  45. namespace OCA\User_LDAP;
  46. use Exception;
  47. use OCP\Cache\CappedMemoryCache;
  48. use OCP\GroupInterface;
  49. use OCP\Group\Backend\IDeleteGroupBackend;
  50. use OCP\Group\Backend\IGetDisplayNameBackend;
  51. use OC\ServerNotAvailableException;
  52. use Psr\Log\LoggerInterface;
  53. class Group_LDAP extends BackendUtility implements GroupInterface, IGroupLDAP, IGetDisplayNameBackend, IDeleteGroupBackend {
  54. protected bool $enabled = false;
  55. /** @var CappedMemoryCache<string[]> $cachedGroupMembers array of users with gid as key */
  56. protected CappedMemoryCache $cachedGroupMembers;
  57. /** @var CappedMemoryCache<array[]> $cachedGroupsByMember array of groups with uid as key */
  58. protected CappedMemoryCache $cachedGroupsByMember;
  59. /** @var CappedMemoryCache<string[]> $cachedNestedGroups array of groups with gid (DN) as key */
  60. protected CappedMemoryCache $cachedNestedGroups;
  61. protected GroupPluginManager $groupPluginManager;
  62. protected LoggerInterface $logger;
  63. /**
  64. * @var string $ldapGroupMemberAssocAttr contains the LDAP setting (in lower case) with the same name
  65. */
  66. protected string $ldapGroupMemberAssocAttr;
  67. public function __construct(Access $access, GroupPluginManager $groupPluginManager) {
  68. parent::__construct($access);
  69. $filter = $this->access->connection->ldapGroupFilter;
  70. $gAssoc = $this->access->connection->ldapGroupMemberAssocAttr;
  71. if (!empty($filter) && !empty($gAssoc)) {
  72. $this->enabled = true;
  73. }
  74. $this->cachedGroupMembers = new CappedMemoryCache();
  75. $this->cachedGroupsByMember = new CappedMemoryCache();
  76. $this->cachedNestedGroups = new CappedMemoryCache();
  77. $this->groupPluginManager = $groupPluginManager;
  78. $this->logger = \OCP\Server::get(LoggerInterface::class);
  79. $this->ldapGroupMemberAssocAttr = strtolower((string)$gAssoc);
  80. }
  81. /**
  82. * Check if user is in group
  83. *
  84. * @param string $uid uid of the user
  85. * @param string $gid gid of the group
  86. * @throws Exception
  87. * @throws ServerNotAvailableException
  88. */
  89. public function inGroup($uid, $gid): bool {
  90. if (!$this->enabled) {
  91. return false;
  92. }
  93. $cacheKey = 'inGroup' . $uid . ':' . $gid;
  94. $inGroup = $this->access->connection->getFromCache($cacheKey);
  95. if (!is_null($inGroup)) {
  96. return (bool)$inGroup;
  97. }
  98. $userDN = $this->access->username2dn($uid);
  99. if (isset($this->cachedGroupMembers[$gid])) {
  100. return in_array($userDN, $this->cachedGroupMembers[$gid]);
  101. }
  102. $cacheKeyMembers = 'inGroup-members:' . $gid;
  103. $members = $this->access->connection->getFromCache($cacheKeyMembers);
  104. if (!is_null($members)) {
  105. $this->cachedGroupMembers[$gid] = $members;
  106. $isInGroup = in_array($userDN, $members, true);
  107. $this->access->connection->writeToCache($cacheKey, $isInGroup);
  108. return $isInGroup;
  109. }
  110. $groupDN = $this->access->groupname2dn($gid);
  111. // just in case
  112. if (!$groupDN || !$userDN) {
  113. $this->access->connection->writeToCache($cacheKey, false);
  114. return false;
  115. }
  116. //check primary group first
  117. if ($gid === $this->getUserPrimaryGroup($userDN)) {
  118. $this->access->connection->writeToCache($cacheKey, true);
  119. return true;
  120. }
  121. //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
  122. $members = $this->_groupMembers($groupDN);
  123. //extra work if we don't get back user DNs
  124. switch ($this->ldapGroupMemberAssocAttr) {
  125. case 'memberuid':
  126. case 'zimbramailforwardingaddress':
  127. $requestAttributes = $this->access->userManager->getAttributes(true);
  128. $users = [];
  129. $filterParts = [];
  130. $bytes = 0;
  131. foreach ($members as $mid) {
  132. if ($this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress') {
  133. $parts = explode('@', $mid); //making sure we get only the uid
  134. $mid = $parts[0];
  135. }
  136. $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
  137. $filterParts[] = $filter;
  138. $bytes += strlen($filter);
  139. if ($bytes >= 9000000) {
  140. // AD has a default input buffer of 10 MB, we do not want
  141. // to take even the chance to exceed it
  142. // so we fetch results with the filterParts we collected so far
  143. $filter = $this->access->combineFilterWithOr($filterParts);
  144. $search = $this->access->fetchListOfUsers($filter, $requestAttributes, count($filterParts));
  145. $bytes = 0;
  146. $filterParts = [];
  147. $users = array_merge($users, $search);
  148. }
  149. }
  150. if (count($filterParts) > 0) {
  151. // if there are filterParts left we need to add their result
  152. $filter = $this->access->combineFilterWithOr($filterParts);
  153. $search = $this->access->fetchListOfUsers($filter, $requestAttributes, count($filterParts));
  154. $users = array_merge($users, $search);
  155. }
  156. // now we cleanup the users array to get only dns
  157. $dns = [];
  158. foreach ($users as $record) {
  159. $dns[$record['dn'][0]] = 1;
  160. }
  161. $members = array_keys($dns);
  162. break;
  163. }
  164. if (count($members) === 0) {
  165. $this->access->connection->writeToCache($cacheKey, false);
  166. return false;
  167. }
  168. $isInGroup = in_array($userDN, $members);
  169. $this->access->connection->writeToCache($cacheKey, $isInGroup);
  170. $this->access->connection->writeToCache($cacheKeyMembers, $members);
  171. $this->cachedGroupMembers[$gid] = $members;
  172. return $isInGroup;
  173. }
  174. /**
  175. * For a group that has user membership defined by an LDAP search url
  176. * attribute returns the users that match the search url otherwise returns
  177. * an empty array.
  178. *
  179. * @throws ServerNotAvailableException
  180. */
  181. public function getDynamicGroupMembers(string $dnGroup): array {
  182. $dynamicGroupMemberURL = strtolower((string)$this->access->connection->ldapDynamicGroupMemberURL);
  183. if (empty($dynamicGroupMemberURL)) {
  184. return [];
  185. }
  186. $dynamicMembers = [];
  187. $memberURLs = $this->access->readAttribute(
  188. $dnGroup,
  189. $dynamicGroupMemberURL,
  190. $this->access->connection->ldapGroupFilter
  191. );
  192. if ($memberURLs !== false) {
  193. // this group has the 'memberURL' attribute so this is a dynamic group
  194. // example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice)
  195. // example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500))
  196. $pos = strpos($memberURLs[0], '(');
  197. if ($pos !== false) {
  198. $memberUrlFilter = substr($memberURLs[0], $pos);
  199. $foundMembers = $this->access->searchUsers($memberUrlFilter, ['dn']);
  200. $dynamicMembers = [];
  201. foreach ($foundMembers as $value) {
  202. $dynamicMembers[$value['dn'][0]] = 1;
  203. }
  204. } else {
  205. $this->logger->debug('No search filter found on member url of group {dn}',
  206. [
  207. 'app' => 'user_ldap',
  208. 'dn' => $dnGroup,
  209. ]
  210. );
  211. }
  212. }
  213. return $dynamicMembers;
  214. }
  215. /**
  216. * Get group members from dn.
  217. * @psalm-param array<string, bool> $seen List of DN that have already been processed.
  218. * @throws ServerNotAvailableException
  219. */
  220. private function _groupMembers(string $dnGroup, array $seen = [], bool &$recursive = false): array {
  221. if (isset($seen[$dnGroup])) {
  222. $recursive = true;
  223. return [];
  224. }
  225. $seen[$dnGroup] = true;
  226. // used extensively in cron job, caching makes sense for nested groups
  227. $cacheKey = '_groupMembers' . $dnGroup;
  228. $groupMembers = $this->access->connection->getFromCache($cacheKey);
  229. if ($groupMembers !== null) {
  230. return $groupMembers;
  231. }
  232. if ($this->access->connection->ldapNestedGroups
  233. && $this->access->connection->useMemberOfToDetectMembership
  234. && $this->access->connection->hasMemberOfFilterSupport
  235. && $this->access->connection->ldapMatchingRuleInChainState !== Configuration::LDAP_SERVER_FEATURE_UNAVAILABLE
  236. ) {
  237. $attemptedLdapMatchingRuleInChain = true;
  238. // Use matching rule 1.2.840.113556.1.4.1941 if available (LDAP_MATCHING_RULE_IN_CHAIN)
  239. $filter = $this->access->combineFilterWithAnd([
  240. $this->access->connection->ldapUserFilter,
  241. $this->access->connection->ldapUserDisplayName . '=*',
  242. 'memberof:1.2.840.113556.1.4.1941:=' . $dnGroup
  243. ]);
  244. $memberRecords = $this->access->fetchListOfUsers(
  245. $filter,
  246. $this->access->userManager->getAttributes(true)
  247. );
  248. $result = array_reduce($memberRecords, function ($carry, $record) {
  249. $carry[] = $record['dn'][0];
  250. return $carry;
  251. }, []);
  252. if ($this->access->connection->ldapMatchingRuleInChainState === Configuration::LDAP_SERVER_FEATURE_AVAILABLE) {
  253. $this->access->connection->writeToCache($cacheKey, $result);
  254. return $result;
  255. } elseif (!empty($memberRecords)) {
  256. $this->access->connection->ldapMatchingRuleInChainState = Configuration::LDAP_SERVER_FEATURE_AVAILABLE;
  257. $this->access->connection->saveConfiguration();
  258. $this->access->connection->writeToCache($cacheKey, $result);
  259. return $result;
  260. }
  261. // when feature availability is unknown, and the result is empty, continue and test with original approach
  262. }
  263. $allMembers = [];
  264. $members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr);
  265. if (is_array($members)) {
  266. if ((int)$this->access->connection->ldapNestedGroups === 1) {
  267. while ($recordDn = array_shift($members)) {
  268. $nestedMembers = $this->_groupMembers($recordDn, $seen, $recursive);
  269. if (!empty($nestedMembers)) {
  270. // Group, queue its members for processing
  271. $members = array_merge($members, $nestedMembers);
  272. } else {
  273. // User (or empty group, or previously seen group), add it to the member list
  274. $allMembers[] = $recordDn;
  275. }
  276. }
  277. } else {
  278. $allMembers = $members;
  279. }
  280. }
  281. $allMembers += $this->getDynamicGroupMembers($dnGroup);
  282. $allMembers = array_unique($allMembers);
  283. // A group cannot be a member of itself
  284. $index = array_search($dnGroup, $allMembers, true);
  285. if ($index !== false) {
  286. unset($allMembers[$index]);
  287. }
  288. if (!$recursive) {
  289. $this->access->connection->writeToCache($cacheKey, $allMembers);
  290. }
  291. if (isset($attemptedLdapMatchingRuleInChain)
  292. && $this->access->connection->ldapMatchingRuleInChainState === Configuration::LDAP_SERVER_FEATURE_UNKNOWN
  293. && !empty($allMembers)
  294. ) {
  295. $this->access->connection->ldapMatchingRuleInChainState = Configuration::LDAP_SERVER_FEATURE_UNAVAILABLE;
  296. $this->access->connection->saveConfiguration();
  297. }
  298. return $allMembers;
  299. }
  300. /**
  301. * @return string[]
  302. * @throws ServerNotAvailableException
  303. */
  304. private function _getGroupDNsFromMemberOf(string $dn, array &$seen = []): array {
  305. if (isset($seen[$dn])) {
  306. return [];
  307. }
  308. $seen[$dn] = true;
  309. if (isset($this->cachedNestedGroups[$dn])) {
  310. return $this->cachedNestedGroups[$dn];
  311. }
  312. $allGroups = [];
  313. $groups = $this->access->readAttribute($dn, 'memberOf');
  314. if (is_array($groups)) {
  315. if ((int)$this->access->connection->ldapNestedGroups === 1) {
  316. while ($recordDn = array_shift($groups)) {
  317. $nestedParents = $this->_getGroupDNsFromMemberOf($recordDn, $seen);
  318. $groups = array_merge($groups, $nestedParents);
  319. $allGroups[] = $recordDn;
  320. }
  321. } else {
  322. $allGroups = $groups;
  323. }
  324. }
  325. // We do not perform array_unique here at it is done in getUserGroups later
  326. $this->cachedNestedGroups[$dn] = $allGroups;
  327. return $this->filterValidGroups($allGroups);
  328. }
  329. /**
  330. * Translates a gidNumber into the Nextcloud internal name.
  331. *
  332. * @return string|false The nextcloud internal name.
  333. * @throws Exception
  334. * @throws ServerNotAvailableException
  335. */
  336. public function gidNumber2Name(string $gid, string $dn) {
  337. $cacheKey = 'gidNumberToName' . $gid;
  338. $groupName = $this->access->connection->getFromCache($cacheKey);
  339. if (!is_null($groupName) && isset($groupName)) {
  340. return $groupName;
  341. }
  342. //we need to get the DN from LDAP
  343. $filter = $this->access->combineFilterWithAnd([
  344. $this->access->connection->ldapGroupFilter,
  345. 'objectClass=posixGroup',
  346. $this->access->connection->ldapGidNumber . '=' . $gid
  347. ]);
  348. return $this->getNameOfGroup($filter, $cacheKey) ?? false;
  349. }
  350. /**
  351. * @return string|null|false The name of the group
  352. * @throws ServerNotAvailableException
  353. * @throws Exception
  354. */
  355. private function getNameOfGroup(string $filter, string $cacheKey) {
  356. $result = $this->access->searchGroups($filter, ['dn'], 1);
  357. if (empty($result)) {
  358. $this->access->connection->writeToCache($cacheKey, false);
  359. return null;
  360. }
  361. $dn = $result[0]['dn'][0];
  362. //and now the group name
  363. //NOTE once we have separate Nextcloud group IDs and group names we can
  364. //directly read the display name attribute instead of the DN
  365. $name = $this->access->dn2groupname($dn);
  366. $this->access->connection->writeToCache($cacheKey, $name);
  367. return $name;
  368. }
  369. /**
  370. * @return string|bool The entry's gidNumber
  371. * @throws ServerNotAvailableException
  372. */
  373. private function getEntryGidNumber(string $dn, string $attribute) {
  374. $value = $this->access->readAttribute($dn, $attribute);
  375. if (is_array($value) && !empty($value)) {
  376. return $value[0];
  377. }
  378. return false;
  379. }
  380. /**
  381. * @return string|bool The group's gidNumber
  382. * @throws ServerNotAvailableException
  383. */
  384. public function getGroupGidNumber(string $dn) {
  385. return $this->getEntryGidNumber($dn, 'gidNumber');
  386. }
  387. /**
  388. * @return string|bool The user's gidNumber
  389. * @throws ServerNotAvailableException
  390. */
  391. public function getUserGidNumber(string $dn) {
  392. $gidNumber = false;
  393. if ($this->access->connection->hasGidNumber) {
  394. $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
  395. if ($gidNumber === false) {
  396. $this->access->connection->hasGidNumber = false;
  397. }
  398. }
  399. return $gidNumber;
  400. }
  401. /**
  402. * @throws ServerNotAvailableException
  403. * @throws Exception
  404. */
  405. private function prepareFilterForUsersHasGidNumber(string $groupDN, string $search = ''): string {
  406. $groupID = $this->getGroupGidNumber($groupDN);
  407. if ($groupID === false) {
  408. throw new Exception('Not a valid group');
  409. }
  410. $filterParts = [];
  411. $filterParts[] = $this->access->getFilterForUserCount();
  412. if ($search !== '') {
  413. $filterParts[] = $this->access->getFilterPartForUserSearch($search);
  414. }
  415. $filterParts[] = $this->access->connection->ldapGidNumber . '=' . $groupID;
  416. return $this->access->combineFilterWithAnd($filterParts);
  417. }
  418. /**
  419. * @return array A list of users that have the given group as gid number
  420. * @throws ServerNotAvailableException
  421. */
  422. public function getUsersInGidNumber(
  423. string $groupDN,
  424. string $search = '',
  425. ?int $limit = -1,
  426. ?int $offset = 0
  427. ): array {
  428. try {
  429. $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
  430. $users = $this->access->fetchListOfUsers(
  431. $filter,
  432. [$this->access->connection->ldapUserDisplayName, 'dn'],
  433. $limit,
  434. $offset
  435. );
  436. return $this->access->nextcloudUserNames($users);
  437. } catch (ServerNotAvailableException $e) {
  438. throw $e;
  439. } catch (Exception $e) {
  440. return [];
  441. }
  442. }
  443. /**
  444. * @throws ServerNotAvailableException
  445. * @return false|string
  446. */
  447. public function getUserGroupByGid(string $dn) {
  448. $groupID = $this->getUserGidNumber($dn);
  449. if ($groupID !== false) {
  450. $groupName = $this->gidNumber2Name($groupID, $dn);
  451. if ($groupName !== false) {
  452. return $groupName;
  453. }
  454. }
  455. return false;
  456. }
  457. /**
  458. * Translates a primary group ID into an Nextcloud internal name
  459. *
  460. * @return string|false
  461. * @throws Exception
  462. * @throws ServerNotAvailableException
  463. */
  464. public function primaryGroupID2Name(string $gid, string $dn) {
  465. $cacheKey = 'primaryGroupIDtoName_' . $gid;
  466. $groupName = $this->access->connection->getFromCache($cacheKey);
  467. if (!is_null($groupName)) {
  468. return $groupName;
  469. }
  470. $domainObjectSid = $this->access->getSID($dn);
  471. if ($domainObjectSid === false) {
  472. return false;
  473. }
  474. //we need to get the DN from LDAP
  475. $filter = $this->access->combineFilterWithAnd([
  476. $this->access->connection->ldapGroupFilter,
  477. 'objectsid=' . $domainObjectSid . '-' . $gid
  478. ]);
  479. return $this->getNameOfGroup($filter, $cacheKey) ?? false;
  480. }
  481. /**
  482. * @return string|false The entry's group Id
  483. * @throws ServerNotAvailableException
  484. */
  485. private function getEntryGroupID(string $dn, string $attribute) {
  486. $value = $this->access->readAttribute($dn, $attribute);
  487. if (is_array($value) && !empty($value)) {
  488. return $value[0];
  489. }
  490. return false;
  491. }
  492. /**
  493. * @return string|false The entry's primary group Id
  494. * @throws ServerNotAvailableException
  495. */
  496. public function getGroupPrimaryGroupID(string $dn) {
  497. return $this->getEntryGroupID($dn, 'primaryGroupToken');
  498. }
  499. /**
  500. * @return string|false
  501. * @throws ServerNotAvailableException
  502. */
  503. public function getUserPrimaryGroupIDs(string $dn) {
  504. $primaryGroupID = false;
  505. if ($this->access->connection->hasPrimaryGroups) {
  506. $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
  507. if ($primaryGroupID === false) {
  508. $this->access->connection->hasPrimaryGroups = false;
  509. }
  510. }
  511. return $primaryGroupID;
  512. }
  513. /**
  514. * @throws Exception
  515. * @throws ServerNotAvailableException
  516. */
  517. private function prepareFilterForUsersInPrimaryGroup(string $groupDN, string $search = ''): string {
  518. $groupID = $this->getGroupPrimaryGroupID($groupDN);
  519. if ($groupID === false) {
  520. throw new Exception('Not a valid group');
  521. }
  522. $filterParts = [];
  523. $filterParts[] = $this->access->getFilterForUserCount();
  524. if ($search !== '') {
  525. $filterParts[] = $this->access->getFilterPartForUserSearch($search);
  526. }
  527. $filterParts[] = 'primaryGroupID=' . $groupID;
  528. return $this->access->combineFilterWithAnd($filterParts);
  529. }
  530. /**
  531. * @throws ServerNotAvailableException
  532. */
  533. public function getUsersInPrimaryGroup(
  534. string $groupDN,
  535. string $search = '',
  536. ?int $limit = -1,
  537. ?int $offset = 0
  538. ): array {
  539. try {
  540. $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
  541. $users = $this->access->fetchListOfUsers(
  542. $filter,
  543. [$this->access->connection->ldapUserDisplayName, 'dn'],
  544. $limit,
  545. $offset
  546. );
  547. return $this->access->nextcloudUserNames($users);
  548. } catch (ServerNotAvailableException $e) {
  549. throw $e;
  550. } catch (Exception $e) {
  551. return [];
  552. }
  553. }
  554. /**
  555. * @throws ServerNotAvailableException
  556. */
  557. public function countUsersInPrimaryGroup(
  558. string $groupDN,
  559. string $search = '',
  560. int $limit = -1,
  561. int $offset = 0
  562. ): int {
  563. try {
  564. $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
  565. $users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
  566. return (int)$users;
  567. } catch (ServerNotAvailableException $e) {
  568. throw $e;
  569. } catch (Exception $e) {
  570. return 0;
  571. }
  572. }
  573. /**
  574. * @return string|false
  575. * @throws ServerNotAvailableException
  576. */
  577. public function getUserPrimaryGroup(string $dn) {
  578. $groupID = $this->getUserPrimaryGroupIDs($dn);
  579. if ($groupID !== false) {
  580. $groupName = $this->primaryGroupID2Name($groupID, $dn);
  581. if ($groupName !== false) {
  582. return $groupName;
  583. }
  584. }
  585. return false;
  586. }
  587. /**
  588. * This function fetches all groups a user belongs to. It does not check
  589. * if the user exists at all.
  590. *
  591. * This function includes groups based on dynamic group membership.
  592. *
  593. * @param string $uid Name of the user
  594. * @return string[] Group names
  595. * @throws Exception
  596. * @throws ServerNotAvailableException
  597. */
  598. public function getUserGroups($uid) {
  599. if (!$this->enabled) {
  600. return [];
  601. }
  602. $cacheKey = 'getUserGroups' . $uid;
  603. $userGroups = $this->access->connection->getFromCache($cacheKey);
  604. if (!is_null($userGroups)) {
  605. return $userGroups;
  606. }
  607. $userDN = $this->access->username2dn($uid);
  608. if (!$userDN) {
  609. $this->access->connection->writeToCache($cacheKey, []);
  610. return [];
  611. }
  612. $groups = [];
  613. $primaryGroup = $this->getUserPrimaryGroup($userDN);
  614. $gidGroupName = $this->getUserGroupByGid($userDN);
  615. $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
  616. if (!empty($dynamicGroupMemberURL)) {
  617. // look through dynamic groups to add them to the result array if needed
  618. $groupsToMatch = $this->access->fetchListOfGroups(
  619. $this->access->connection->ldapGroupFilter, ['dn', $dynamicGroupMemberURL]);
  620. foreach ($groupsToMatch as $dynamicGroup) {
  621. if (!isset($dynamicGroup[$dynamicGroupMemberURL][0])) {
  622. continue;
  623. }
  624. $pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
  625. if ($pos !== false) {
  626. $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0], $pos);
  627. // apply filter via ldap search to see if this user is in this
  628. // dynamic group
  629. $userMatch = $this->access->readAttribute(
  630. $userDN,
  631. $this->access->connection->ldapUserDisplayName,
  632. $memberUrlFilter
  633. );
  634. if ($userMatch !== false) {
  635. // match found so this user is in this group
  636. $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
  637. if (is_string($groupName)) {
  638. // be sure to never return false if the dn could not be
  639. // resolved to a name, for whatever reason.
  640. $groups[] = $groupName;
  641. }
  642. }
  643. } else {
  644. $this->logger->debug('No search filter found on member url of group {dn}',
  645. [
  646. 'app' => 'user_ldap',
  647. 'dn' => $dynamicGroup,
  648. ]
  649. );
  650. }
  651. }
  652. }
  653. // if possible, read out membership via memberOf. It's far faster than
  654. // performing a search, which still is a fallback later.
  655. // memberof doesn't support memberuid, so skip it here.
  656. if ((int)$this->access->connection->hasMemberOfFilterSupport === 1
  657. && (int)$this->access->connection->useMemberOfToDetectMembership === 1
  658. && $this->ldapGroupMemberAssocAttr !== 'memberuid'
  659. && $this->ldapGroupMemberAssocAttr !== 'zimbramailforwardingaddress') {
  660. $groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
  661. foreach ($groupDNs as $dn) {
  662. $groupName = $this->access->dn2groupname($dn);
  663. if (is_string($groupName)) {
  664. // be sure to never return false if the dn could not be
  665. // resolved to a name, for whatever reason.
  666. $groups[] = $groupName;
  667. }
  668. }
  669. } else {
  670. // uniqueMember takes DN, memberuid the uid, so we need to distinguish
  671. switch ($this->ldapGroupMemberAssocAttr) {
  672. case 'uniquemember':
  673. case 'member':
  674. $uid = $userDN;
  675. break;
  676. case 'memberuid':
  677. case 'zimbramailforwardingaddress':
  678. $result = $this->access->readAttribute($userDN, 'uid');
  679. if ($result === false) {
  680. $this->logger->debug('No uid attribute found for DN {dn} on {host}',
  681. [
  682. 'app' => 'user_ldap',
  683. 'dn' => $userDN,
  684. 'host' => $this->access->connection->ldapHost,
  685. ]
  686. );
  687. $uid = false;
  688. } else {
  689. $uid = $result[0];
  690. }
  691. break;
  692. default:
  693. // just in case
  694. $uid = $userDN;
  695. break;
  696. }
  697. if ($uid !== false) {
  698. $groupsByMember = array_values($this->getGroupsByMember($uid));
  699. $groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
  700. $groups = array_merge($groups, $groupsByMember);
  701. }
  702. }
  703. if ($primaryGroup !== false) {
  704. $groups[] = $primaryGroup;
  705. }
  706. if ($gidGroupName !== false) {
  707. $groups[] = $gidGroupName;
  708. }
  709. $groups = array_unique($groups, SORT_LOCALE_STRING);
  710. $this->access->connection->writeToCache($cacheKey, $groups);
  711. return $groups;
  712. }
  713. /**
  714. * @return array[]
  715. * @throws ServerNotAvailableException
  716. */
  717. private function getGroupsByMember(string $dn, array &$seen = []): array {
  718. if (isset($seen[$dn])) {
  719. return [];
  720. }
  721. $seen[$dn] = true;
  722. if (isset($this->cachedGroupsByMember[$dn])) {
  723. return $this->cachedGroupsByMember[$dn];
  724. }
  725. $filter = $this->access->connection->ldapGroupMemberAssocAttr . '=' . $dn;
  726. if ($this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress') {
  727. //in this case the member entries are email addresses
  728. $filter .= '@*';
  729. }
  730. $nesting = (int)$this->access->connection->ldapNestedGroups;
  731. if ($nesting === 0) {
  732. $filter = $this->access->combineFilterWithAnd([$filter, $this->access->connection->ldapGroupFilter]);
  733. }
  734. $allGroups = [];
  735. $groups = $this->access->fetchListOfGroups($filter,
  736. [strtolower($this->access->connection->ldapGroupMemberAssocAttr), $this->access->connection->ldapGroupDisplayName, 'dn']);
  737. if ($nesting === 1) {
  738. while ($record = array_shift($groups)) {
  739. // Note: this has no effect when ldapGroupMemberAssocAttr is uid based
  740. $nestedParents = $this->getGroupsByMember($record['dn'][0], $seen);
  741. $groups = array_merge($groups, $nestedParents);
  742. $allGroups[] = $record;
  743. }
  744. } else {
  745. $allGroups = $groups;
  746. }
  747. $visibleGroups = $this->filterValidGroups($allGroups);
  748. $this->cachedGroupsByMember[$dn] = $visibleGroups;
  749. return $visibleGroups;
  750. }
  751. /**
  752. * get a list of all users in a group
  753. *
  754. * @param string $gid
  755. * @param string $search
  756. * @param int $limit
  757. * @param int $offset
  758. * @return array with user ids
  759. * @throws Exception
  760. * @throws ServerNotAvailableException
  761. */
  762. public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
  763. if (!$this->enabled) {
  764. return [];
  765. }
  766. if (!$this->groupExists($gid)) {
  767. return [];
  768. }
  769. $search = $this->access->escapeFilterPart($search, true);
  770. $cacheKey = 'usersInGroup-' . $gid . '-' . $search . '-' . $limit . '-' . $offset;
  771. // check for cache of the exact query
  772. $groupUsers = $this->access->connection->getFromCache($cacheKey);
  773. if (!is_null($groupUsers)) {
  774. return $groupUsers;
  775. }
  776. if ($limit === -1) {
  777. $limit = null;
  778. }
  779. // check for cache of the query without limit and offset
  780. $groupUsers = $this->access->connection->getFromCache('usersInGroup-' . $gid . '-' . $search);
  781. if (!is_null($groupUsers)) {
  782. $groupUsers = array_slice($groupUsers, $offset, $limit);
  783. $this->access->connection->writeToCache($cacheKey, $groupUsers);
  784. return $groupUsers;
  785. }
  786. $groupDN = $this->access->groupname2dn($gid);
  787. if (!$groupDN) {
  788. // group couldn't be found, return empty result-set
  789. $this->access->connection->writeToCache($cacheKey, []);
  790. return [];
  791. }
  792. $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
  793. $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
  794. $members = $this->_groupMembers($groupDN);
  795. if (!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
  796. //in case users could not be retrieved, return empty result set
  797. $this->access->connection->writeToCache($cacheKey, []);
  798. return [];
  799. }
  800. $groupUsers = [];
  801. $attrs = $this->access->userManager->getAttributes(true);
  802. foreach ($members as $member) {
  803. switch ($this->ldapGroupMemberAssocAttr) {
  804. /** @noinspection PhpMissingBreakStatementInspection */
  805. case 'zimbramailforwardingaddress':
  806. //we get email addresses and need to convert them to uids
  807. $parts = explode('@', $member);
  808. $member = $parts[0];
  809. //no break needed because we just needed to remove the email part and now we have uids
  810. case 'memberuid':
  811. //we got uids, need to get their DNs to 'translate' them to user names
  812. $filter = $this->access->combineFilterWithAnd([
  813. str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
  814. $this->access->combineFilterWithAnd([
  815. $this->access->getFilterPartForUserSearch($search),
  816. $this->access->connection->ldapUserFilter
  817. ])
  818. ]);
  819. $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
  820. if (empty($ldap_users)) {
  821. break;
  822. }
  823. $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
  824. break;
  825. default:
  826. //we got DNs, check if we need to filter by search or we can give back all of them
  827. $uid = $this->access->dn2username($member);
  828. if (!$uid) {
  829. break;
  830. }
  831. $cacheKey = 'userExistsOnLDAP' . $uid;
  832. $userExists = $this->access->connection->getFromCache($cacheKey);
  833. if ($userExists === false) {
  834. break;
  835. }
  836. if ($userExists === null || $search !== '') {
  837. if (!$this->access->readAttribute($member,
  838. $this->access->connection->ldapUserDisplayName,
  839. $this->access->combineFilterWithAnd([
  840. $this->access->getFilterPartForUserSearch($search),
  841. $this->access->connection->ldapUserFilter
  842. ]))) {
  843. if ($search === '') {
  844. $this->access->connection->writeToCache($cacheKey, false);
  845. }
  846. break;
  847. }
  848. $this->access->connection->writeToCache($cacheKey, true);
  849. }
  850. $groupUsers[] = $uid;
  851. break;
  852. }
  853. }
  854. $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
  855. natsort($groupUsers);
  856. $this->access->connection->writeToCache('usersInGroup-' . $gid . '-' . $search, $groupUsers);
  857. $groupUsers = array_slice($groupUsers, $offset, $limit);
  858. $this->access->connection->writeToCache($cacheKey, $groupUsers);
  859. return $groupUsers;
  860. }
  861. /**
  862. * returns the number of users in a group, who match the search term
  863. *
  864. * @param string $gid the internal group name
  865. * @param string $search optional, a search string
  866. * @return int|bool
  867. * @throws Exception
  868. * @throws ServerNotAvailableException
  869. */
  870. public function countUsersInGroup($gid, $search = '') {
  871. if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) {
  872. return $this->groupPluginManager->countUsersInGroup($gid, $search);
  873. }
  874. $cacheKey = 'countUsersInGroup-' . $gid . '-' . $search;
  875. if (!$this->enabled || !$this->groupExists($gid)) {
  876. return false;
  877. }
  878. $groupUsers = $this->access->connection->getFromCache($cacheKey);
  879. if (!is_null($groupUsers)) {
  880. return $groupUsers;
  881. }
  882. $groupDN = $this->access->groupname2dn($gid);
  883. if (!$groupDN) {
  884. // group couldn't be found, return empty result set
  885. $this->access->connection->writeToCache($cacheKey, false);
  886. return false;
  887. }
  888. $members = $this->_groupMembers($groupDN);
  889. $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
  890. if (!$members && $primaryUserCount === 0) {
  891. //in case users could not be retrieved, return empty result set
  892. $this->access->connection->writeToCache($cacheKey, false);
  893. return false;
  894. }
  895. if ($search === '') {
  896. $groupUsers = count($members) + $primaryUserCount;
  897. $this->access->connection->writeToCache($cacheKey, $groupUsers);
  898. return $groupUsers;
  899. }
  900. $search = $this->access->escapeFilterPart($search, true);
  901. $isMemberUid =
  902. ($this->ldapGroupMemberAssocAttr === 'memberuid' ||
  903. $this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress');
  904. //we need to apply the search filter
  905. //alternatives that need to be checked:
  906. //a) get all users by search filter and array_intersect them
  907. //b) a, but only when less than 1k 10k ?k users like it is
  908. //c) put all DNs|uids in a LDAP filter, combine with the search string
  909. // and let it count.
  910. //For now this is not important, because the only use of this method
  911. //does not supply a search string
  912. $groupUsers = [];
  913. foreach ($members as $member) {
  914. if ($isMemberUid) {
  915. if ($this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress') {
  916. //we get email addresses and need to convert them to uids
  917. $parts = explode('@', $member);
  918. $member = $parts[0];
  919. }
  920. //we got uids, need to get their DNs to 'translate' them to user names
  921. $filter = $this->access->combineFilterWithAnd([
  922. str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
  923. $this->access->getFilterPartForUserSearch($search)
  924. ]);
  925. $ldap_users = $this->access->fetchListOfUsers($filter, ['dn'], 1);
  926. if (count($ldap_users) < 1) {
  927. continue;
  928. }
  929. $groupUsers[] = $this->access->dn2username($ldap_users[0]);
  930. } else {
  931. //we need to apply the search filter now
  932. if (!$this->access->readAttribute($member,
  933. $this->access->connection->ldapUserDisplayName,
  934. $this->access->getFilterPartForUserSearch($search))) {
  935. continue;
  936. }
  937. // dn2username will also check if the users belong to the allowed base
  938. if ($ncGroupId = $this->access->dn2username($member)) {
  939. $groupUsers[] = $ncGroupId;
  940. }
  941. }
  942. }
  943. //and get users that have the group as primary
  944. $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
  945. return count($groupUsers) + $primaryUsers;
  946. }
  947. /**
  948. * get a list of all groups using a paged search
  949. *
  950. * @param string $search
  951. * @param int $limit
  952. * @param int $offset
  953. * @return array with group names
  954. *
  955. * Returns a list with all groups
  956. * Uses a paged search if available to override a
  957. * server side search limit.
  958. * (active directory has a limit of 1000 by default)
  959. * @throws Exception
  960. */
  961. public function getGroups($search = '', $limit = -1, $offset = 0) {
  962. if (!$this->enabled) {
  963. return [];
  964. }
  965. $search = $this->access->escapeFilterPart($search, true);
  966. $cacheKey = 'getGroups-' . $search . '-' . $limit . '-' . $offset;
  967. //Check cache before driving unnecessary searches
  968. $ldap_groups = $this->access->connection->getFromCache($cacheKey);
  969. if (!is_null($ldap_groups)) {
  970. return $ldap_groups;
  971. }
  972. // if we'd pass -1 to LDAP search, we'd end up in a Protocol
  973. // error. With a limit of 0, we get 0 results. So we pass null.
  974. if ($limit <= 0) {
  975. $limit = null;
  976. }
  977. $filter = $this->access->combineFilterWithAnd([
  978. $this->access->connection->ldapGroupFilter,
  979. $this->access->getFilterPartForGroupSearch($search)
  980. ]);
  981. $ldap_groups = $this->access->fetchListOfGroups($filter,
  982. [$this->access->connection->ldapGroupDisplayName, 'dn'],
  983. $limit,
  984. $offset);
  985. $ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
  986. $this->access->connection->writeToCache($cacheKey, $ldap_groups);
  987. return $ldap_groups;
  988. }
  989. /**
  990. * check if a group exists
  991. *
  992. * @param string $gid
  993. * @return bool
  994. * @throws ServerNotAvailableException
  995. */
  996. public function groupExists($gid) {
  997. $groupExists = $this->access->connection->getFromCache('groupExists' . $gid);
  998. if (!is_null($groupExists)) {
  999. return (bool)$groupExists;
  1000. }
  1001. //getting dn, if false the group does not exist. If dn, it may be mapped
  1002. //only, requires more checking.
  1003. $dn = $this->access->groupname2dn($gid);
  1004. if (!$dn) {
  1005. $this->access->connection->writeToCache('groupExists' . $gid, false);
  1006. return false;
  1007. }
  1008. if (!$this->access->isDNPartOfBase($dn, $this->access->connection->ldapBaseGroups)) {
  1009. $this->access->connection->writeToCache('groupExists' . $gid, false);
  1010. return false;
  1011. }
  1012. //if group really still exists, we will be able to read its objectClass
  1013. if (!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapGroupFilter))) {
  1014. $this->access->connection->writeToCache('groupExists' . $gid, false);
  1015. return false;
  1016. }
  1017. $this->access->connection->writeToCache('groupExists' . $gid, true);
  1018. return true;
  1019. }
  1020. /**
  1021. * @template T
  1022. * @param array<array-key, T> $listOfGroups
  1023. * @return array<array-key, T>
  1024. * @throws ServerNotAvailableException
  1025. * @throws Exception
  1026. */
  1027. protected function filterValidGroups(array $listOfGroups): array {
  1028. $validGroupDNs = [];
  1029. foreach ($listOfGroups as $key => $item) {
  1030. $dn = is_string($item) ? $item : $item['dn'][0];
  1031. if (is_array($item) && !isset($item[$this->access->connection->ldapGroupDisplayName][0])) {
  1032. continue;
  1033. }
  1034. $name = $item[$this->access->connection->ldapGroupDisplayName][0] ?? null;
  1035. $gid = $this->access->dn2groupname($dn, $name);
  1036. if (!$gid) {
  1037. continue;
  1038. }
  1039. if ($this->groupExists($gid)) {
  1040. $validGroupDNs[$key] = $item;
  1041. }
  1042. }
  1043. return $validGroupDNs;
  1044. }
  1045. /**
  1046. * Check if backend implements actions
  1047. *
  1048. * @param int $actions bitwise-or'ed actions
  1049. * @return boolean
  1050. *
  1051. * Returns the supported actions as int to be
  1052. * compared with GroupInterface::CREATE_GROUP etc.
  1053. */
  1054. public function implementsActions($actions) {
  1055. return (bool)((GroupInterface::COUNT_USERS |
  1056. GroupInterface::DELETE_GROUP |
  1057. $this->groupPluginManager->getImplementedActions()) & $actions);
  1058. }
  1059. /**
  1060. * Return access for LDAP interaction.
  1061. *
  1062. * @return Access instance of Access for LDAP interaction
  1063. */
  1064. public function getLDAPAccess($gid) {
  1065. return $this->access;
  1066. }
  1067. /**
  1068. * create a group
  1069. *
  1070. * @param string $gid
  1071. * @return bool
  1072. * @throws Exception
  1073. * @throws ServerNotAvailableException
  1074. */
  1075. public function createGroup($gid) {
  1076. if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) {
  1077. if ($dn = $this->groupPluginManager->createGroup($gid)) {
  1078. //updates group mapping
  1079. $uuid = $this->access->getUUID($dn, false);
  1080. if (is_string($uuid)) {
  1081. $this->access->mapAndAnnounceIfApplicable(
  1082. $this->access->getGroupMapper(),
  1083. $dn,
  1084. $gid,
  1085. $uuid,
  1086. false
  1087. );
  1088. $this->access->cacheGroupExists($gid);
  1089. }
  1090. }
  1091. return $dn != null;
  1092. }
  1093. throw new Exception('Could not create group in LDAP backend.');
  1094. }
  1095. /**
  1096. * delete a group
  1097. *
  1098. * @param string $gid gid of the group to delete
  1099. * @throws Exception
  1100. */
  1101. public function deleteGroup(string $gid): bool {
  1102. if ($this->groupPluginManager->canDeleteGroup()) {
  1103. if ($ret = $this->groupPluginManager->deleteGroup($gid)) {
  1104. // Delete group in nextcloud internal db
  1105. $this->access->getGroupMapper()->unmap($gid);
  1106. $this->access->connection->writeToCache("groupExists" . $gid, false);
  1107. }
  1108. return $ret;
  1109. }
  1110. // Getting dn, if false the group is not mapped
  1111. $dn = $this->access->groupname2dn($gid);
  1112. if (!$dn) {
  1113. throw new Exception('Could not delete unknown group '.$gid.' in LDAP backend.');
  1114. }
  1115. if (!$this->groupExists($gid)) {
  1116. // The group does not exist in the LDAP, remove the mapping
  1117. $this->access->getGroupMapper()->unmap($gid);
  1118. $this->access->connection->writeToCache("groupExists" . $gid, false);
  1119. return true;
  1120. }
  1121. throw new Exception('Could not delete existing group '.$gid.' in LDAP backend.');
  1122. }
  1123. /**
  1124. * Add a user to a group
  1125. *
  1126. * @param string $uid Name of the user to add to group
  1127. * @param string $gid Name of the group in which add the user
  1128. * @return bool
  1129. * @throws Exception
  1130. */
  1131. public function addToGroup($uid, $gid) {
  1132. if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) {
  1133. if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) {
  1134. $this->access->connection->clearCache();
  1135. unset($this->cachedGroupMembers[$gid]);
  1136. }
  1137. return $ret;
  1138. }
  1139. throw new Exception('Could not add user to group in LDAP backend.');
  1140. }
  1141. /**
  1142. * Removes a user from a group
  1143. *
  1144. * @param string $uid Name of the user to remove from group
  1145. * @param string $gid Name of the group from which remove the user
  1146. * @return bool
  1147. * @throws Exception
  1148. */
  1149. public function removeFromGroup($uid, $gid) {
  1150. if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) {
  1151. if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) {
  1152. $this->access->connection->clearCache();
  1153. unset($this->cachedGroupMembers[$gid]);
  1154. }
  1155. return $ret;
  1156. }
  1157. throw new Exception('Could not remove user from group in LDAP backend.');
  1158. }
  1159. /**
  1160. * Gets group details
  1161. *
  1162. * @param string $gid Name of the group
  1163. * @return array|false
  1164. * @throws Exception
  1165. */
  1166. public function getGroupDetails($gid) {
  1167. if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) {
  1168. return $this->groupPluginManager->getGroupDetails($gid);
  1169. }
  1170. throw new Exception('Could not get group details in LDAP backend.');
  1171. }
  1172. /**
  1173. * Return LDAP connection resource from a cloned connection.
  1174. * The cloned connection needs to be closed manually.
  1175. * of the current access.
  1176. *
  1177. * @param string $gid
  1178. * @return resource|\LDAP\Connection The LDAP connection
  1179. * @throws ServerNotAvailableException
  1180. */
  1181. public function getNewLDAPConnection($gid) {
  1182. $connection = clone $this->access->getConnection();
  1183. return $connection->getConnectionResource();
  1184. }
  1185. /**
  1186. * @throws ServerNotAvailableException
  1187. */
  1188. public function getDisplayName(string $gid): string {
  1189. if ($this->groupPluginManager instanceof IGetDisplayNameBackend) {
  1190. return $this->groupPluginManager->getDisplayName($gid);
  1191. }
  1192. $cacheKey = 'group_getDisplayName' . $gid;
  1193. if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
  1194. return $displayName;
  1195. }
  1196. $displayName = $this->access->readAttribute(
  1197. $this->access->groupname2dn($gid),
  1198. $this->access->connection->ldapGroupDisplayName);
  1199. if (($displayName !== false) && (count($displayName) > 0)) {
  1200. $displayName = $displayName[0];
  1201. $this->access->connection->writeToCache($cacheKey, $displayName);
  1202. return $displayName;
  1203. }
  1204. return '';
  1205. }
  1206. }