Group_LDAP.php 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339
  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 OC\ServerNotAvailableException;
  48. use OCP\Cache\CappedMemoryCache;
  49. use OCP\GroupInterface;
  50. use OCP\Group\Backend\IDeleteGroupBackend;
  51. use OCP\Group\Backend\IGetDisplayNameBackend;
  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<int,string> 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. * @return array<int,string>
  533. */
  534. public function getUsersInPrimaryGroup(
  535. string $groupDN,
  536. string $search = '',
  537. ?int $limit = -1,
  538. ?int $offset = 0
  539. ): array {
  540. try {
  541. $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
  542. $users = $this->access->fetchListOfUsers(
  543. $filter,
  544. [$this->access->connection->ldapUserDisplayName, 'dn'],
  545. $limit,
  546. $offset
  547. );
  548. return $this->access->nextcloudUserNames($users);
  549. } catch (ServerNotAvailableException $e) {
  550. throw $e;
  551. } catch (Exception $e) {
  552. return [];
  553. }
  554. }
  555. /**
  556. * @throws ServerNotAvailableException
  557. */
  558. public function countUsersInPrimaryGroup(
  559. string $groupDN,
  560. string $search = '',
  561. int $limit = -1,
  562. int $offset = 0
  563. ): int {
  564. try {
  565. $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
  566. $users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
  567. return (int)$users;
  568. } catch (ServerNotAvailableException $e) {
  569. throw $e;
  570. } catch (Exception $e) {
  571. return 0;
  572. }
  573. }
  574. /**
  575. * @return string|false
  576. * @throws ServerNotAvailableException
  577. */
  578. public function getUserPrimaryGroup(string $dn) {
  579. $groupID = $this->getUserPrimaryGroupIDs($dn);
  580. if ($groupID !== false) {
  581. $groupName = $this->primaryGroupID2Name($groupID, $dn);
  582. if ($groupName !== false) {
  583. return $groupName;
  584. }
  585. }
  586. return false;
  587. }
  588. /**
  589. * This function fetches all groups a user belongs to. It does not check
  590. * if the user exists at all.
  591. *
  592. * This function includes groups based on dynamic group membership.
  593. *
  594. * @param string $uid Name of the user
  595. * @return string[] Group names
  596. * @throws Exception
  597. * @throws ServerNotAvailableException
  598. */
  599. public function getUserGroups($uid) {
  600. if (!$this->enabled) {
  601. return [];
  602. }
  603. $cacheKey = 'getUserGroups' . $uid;
  604. $userGroups = $this->access->connection->getFromCache($cacheKey);
  605. if (!is_null($userGroups)) {
  606. return $userGroups;
  607. }
  608. $userDN = $this->access->username2dn($uid);
  609. if (!$userDN) {
  610. $this->access->connection->writeToCache($cacheKey, []);
  611. return [];
  612. }
  613. $groups = [];
  614. $primaryGroup = $this->getUserPrimaryGroup($userDN);
  615. $gidGroupName = $this->getUserGroupByGid($userDN);
  616. $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
  617. if (!empty($dynamicGroupMemberURL)) {
  618. // look through dynamic groups to add them to the result array if needed
  619. $groupsToMatch = $this->access->fetchListOfGroups(
  620. $this->access->connection->ldapGroupFilter, ['dn', $dynamicGroupMemberURL]);
  621. foreach ($groupsToMatch as $dynamicGroup) {
  622. if (!isset($dynamicGroup[$dynamicGroupMemberURL][0])) {
  623. continue;
  624. }
  625. $pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
  626. if ($pos !== false) {
  627. $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0], $pos);
  628. // apply filter via ldap search to see if this user is in this
  629. // dynamic group
  630. $userMatch = $this->access->readAttribute(
  631. $userDN,
  632. $this->access->connection->ldapUserDisplayName,
  633. $memberUrlFilter
  634. );
  635. if ($userMatch !== false) {
  636. // match found so this user is in this group
  637. $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
  638. if (is_string($groupName)) {
  639. // be sure to never return false if the dn could not be
  640. // resolved to a name, for whatever reason.
  641. $groups[] = $groupName;
  642. }
  643. }
  644. } else {
  645. $this->logger->debug('No search filter found on member url of group {dn}',
  646. [
  647. 'app' => 'user_ldap',
  648. 'dn' => $dynamicGroup,
  649. ]
  650. );
  651. }
  652. }
  653. }
  654. // if possible, read out membership via memberOf. It's far faster than
  655. // performing a search, which still is a fallback later.
  656. // memberof doesn't support memberuid, so skip it here.
  657. if ((int)$this->access->connection->hasMemberOfFilterSupport === 1
  658. && (int)$this->access->connection->useMemberOfToDetectMembership === 1
  659. && $this->ldapGroupMemberAssocAttr !== 'memberuid'
  660. && $this->ldapGroupMemberAssocAttr !== 'zimbramailforwardingaddress') {
  661. $groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
  662. foreach ($groupDNs as $dn) {
  663. $groupName = $this->access->dn2groupname($dn);
  664. if (is_string($groupName)) {
  665. // be sure to never return false if the dn could not be
  666. // resolved to a name, for whatever reason.
  667. $groups[] = $groupName;
  668. }
  669. }
  670. } else {
  671. // uniqueMember takes DN, memberuid the uid, so we need to distinguish
  672. switch ($this->ldapGroupMemberAssocAttr) {
  673. case 'uniquemember':
  674. case 'member':
  675. $uid = $userDN;
  676. break;
  677. case 'memberuid':
  678. case 'zimbramailforwardingaddress':
  679. $result = $this->access->readAttribute($userDN, 'uid');
  680. if ($result === false) {
  681. $this->logger->debug('No uid attribute found for DN {dn} on {host}',
  682. [
  683. 'app' => 'user_ldap',
  684. 'dn' => $userDN,
  685. 'host' => $this->access->connection->ldapHost,
  686. ]
  687. );
  688. $uid = false;
  689. } else {
  690. $uid = $result[0];
  691. }
  692. break;
  693. default:
  694. // just in case
  695. $uid = $userDN;
  696. break;
  697. }
  698. if ($uid !== false) {
  699. $groupsByMember = array_values($this->getGroupsByMember($uid));
  700. $groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
  701. $groups = array_merge($groups, $groupsByMember);
  702. }
  703. }
  704. if ($primaryGroup !== false) {
  705. $groups[] = $primaryGroup;
  706. }
  707. if ($gidGroupName !== false) {
  708. $groups[] = $gidGroupName;
  709. }
  710. $groups = array_unique($groups, SORT_LOCALE_STRING);
  711. $this->access->connection->writeToCache($cacheKey, $groups);
  712. return $groups;
  713. }
  714. /**
  715. * @return array[]
  716. * @throws ServerNotAvailableException
  717. */
  718. private function getGroupsByMember(string $dn, array &$seen = []): array {
  719. if (isset($seen[$dn])) {
  720. return [];
  721. }
  722. $seen[$dn] = true;
  723. if (isset($this->cachedGroupsByMember[$dn])) {
  724. return $this->cachedGroupsByMember[$dn];
  725. }
  726. $filter = $this->access->connection->ldapGroupMemberAssocAttr . '=' . $dn;
  727. if ($this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress') {
  728. //in this case the member entries are email addresses
  729. $filter .= '@*';
  730. }
  731. $nesting = (int)$this->access->connection->ldapNestedGroups;
  732. if ($nesting === 0) {
  733. $filter = $this->access->combineFilterWithAnd([$filter, $this->access->connection->ldapGroupFilter]);
  734. }
  735. $allGroups = [];
  736. $groups = $this->access->fetchListOfGroups($filter,
  737. [strtolower($this->access->connection->ldapGroupMemberAssocAttr), $this->access->connection->ldapGroupDisplayName, 'dn']);
  738. if ($nesting === 1) {
  739. while ($record = array_shift($groups)) {
  740. // Note: this has no effect when ldapGroupMemberAssocAttr is uid based
  741. $nestedParents = $this->getGroupsByMember($record['dn'][0], $seen);
  742. $groups = array_merge($groups, $nestedParents);
  743. $allGroups[] = $record;
  744. }
  745. } else {
  746. $allGroups = $groups;
  747. }
  748. $visibleGroups = $this->filterValidGroups($allGroups);
  749. $this->cachedGroupsByMember[$dn] = $visibleGroups;
  750. return $visibleGroups;
  751. }
  752. /**
  753. * get a list of all users in a group
  754. *
  755. * @param string $gid
  756. * @param string $search
  757. * @param int $limit
  758. * @param int $offset
  759. * @return array<int,string> user ids
  760. * @throws Exception
  761. * @throws ServerNotAvailableException
  762. */
  763. public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
  764. if (!$this->enabled) {
  765. return [];
  766. }
  767. if (!$this->groupExists($gid)) {
  768. return [];
  769. }
  770. $search = $this->access->escapeFilterPart($search, true);
  771. $cacheKey = 'usersInGroup-' . $gid . '-' . $search . '-' . $limit . '-' . $offset;
  772. // check for cache of the exact query
  773. $groupUsers = $this->access->connection->getFromCache($cacheKey);
  774. if (!is_null($groupUsers)) {
  775. return $groupUsers;
  776. }
  777. if ($limit === -1) {
  778. $limit = null;
  779. }
  780. // check for cache of the query without limit and offset
  781. $groupUsers = $this->access->connection->getFromCache('usersInGroup-' . $gid . '-' . $search);
  782. if (!is_null($groupUsers)) {
  783. $groupUsers = array_slice($groupUsers, $offset, $limit);
  784. $this->access->connection->writeToCache($cacheKey, $groupUsers);
  785. return $groupUsers;
  786. }
  787. $groupDN = $this->access->groupname2dn($gid);
  788. if (!$groupDN) {
  789. // group couldn't be found, return empty result-set
  790. $this->access->connection->writeToCache($cacheKey, []);
  791. return [];
  792. }
  793. $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
  794. $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
  795. $members = $this->_groupMembers($groupDN);
  796. if (!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
  797. //in case users could not be retrieved, return empty result set
  798. $this->access->connection->writeToCache($cacheKey, []);
  799. return [];
  800. }
  801. $groupUsers = [];
  802. $attrs = $this->access->userManager->getAttributes(true);
  803. foreach ($members as $member) {
  804. switch ($this->ldapGroupMemberAssocAttr) {
  805. /** @noinspection PhpMissingBreakStatementInspection */
  806. case 'zimbramailforwardingaddress':
  807. //we get email addresses and need to convert them to uids
  808. $parts = explode('@', $member);
  809. $member = $parts[0];
  810. //no break needed because we just needed to remove the email part and now we have uids
  811. case 'memberuid':
  812. //we got uids, need to get their DNs to 'translate' them to user names
  813. $filter = $this->access->combineFilterWithAnd([
  814. str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
  815. $this->access->combineFilterWithAnd([
  816. $this->access->getFilterPartForUserSearch($search),
  817. $this->access->connection->ldapUserFilter
  818. ])
  819. ]);
  820. $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
  821. if (empty($ldap_users)) {
  822. break;
  823. }
  824. $uid = $this->access->dn2username($ldap_users[0]['dn'][0]);
  825. if (!$uid) {
  826. break;
  827. }
  828. $groupUsers[] = $uid;
  829. break;
  830. default:
  831. //we got DNs, check if we need to filter by search or we can give back all of them
  832. $uid = $this->access->dn2username($member);
  833. if (!$uid) {
  834. break;
  835. }
  836. $cacheKey = 'userExistsOnLDAP' . $uid;
  837. $userExists = $this->access->connection->getFromCache($cacheKey);
  838. if ($userExists === false) {
  839. break;
  840. }
  841. if ($userExists === null || $search !== '') {
  842. if (!$this->access->readAttribute($member,
  843. $this->access->connection->ldapUserDisplayName,
  844. $this->access->combineFilterWithAnd([
  845. $this->access->getFilterPartForUserSearch($search),
  846. $this->access->connection->ldapUserFilter
  847. ]))) {
  848. if ($search === '') {
  849. $this->access->connection->writeToCache($cacheKey, false);
  850. }
  851. break;
  852. }
  853. $this->access->connection->writeToCache($cacheKey, true);
  854. }
  855. $groupUsers[] = $uid;
  856. break;
  857. }
  858. }
  859. $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
  860. natsort($groupUsers);
  861. $this->access->connection->writeToCache('usersInGroup-' . $gid . '-' . $search, $groupUsers);
  862. $groupUsers = array_slice($groupUsers, $offset, $limit);
  863. $this->access->connection->writeToCache($cacheKey, $groupUsers);
  864. return $groupUsers;
  865. }
  866. /**
  867. * returns the number of users in a group, who match the search term
  868. *
  869. * @param string $gid the internal group name
  870. * @param string $search optional, a search string
  871. * @return int|bool
  872. * @throws Exception
  873. * @throws ServerNotAvailableException
  874. */
  875. public function countUsersInGroup($gid, $search = '') {
  876. if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) {
  877. return $this->groupPluginManager->countUsersInGroup($gid, $search);
  878. }
  879. $cacheKey = 'countUsersInGroup-' . $gid . '-' . $search;
  880. if (!$this->enabled || !$this->groupExists($gid)) {
  881. return false;
  882. }
  883. $groupUsers = $this->access->connection->getFromCache($cacheKey);
  884. if (!is_null($groupUsers)) {
  885. return $groupUsers;
  886. }
  887. $groupDN = $this->access->groupname2dn($gid);
  888. if (!$groupDN) {
  889. // group couldn't be found, return empty result set
  890. $this->access->connection->writeToCache($cacheKey, false);
  891. return false;
  892. }
  893. $members = $this->_groupMembers($groupDN);
  894. $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
  895. if (!$members && $primaryUserCount === 0) {
  896. //in case users could not be retrieved, return empty result set
  897. $this->access->connection->writeToCache($cacheKey, false);
  898. return false;
  899. }
  900. if ($search === '') {
  901. $groupUsers = count($members) + $primaryUserCount;
  902. $this->access->connection->writeToCache($cacheKey, $groupUsers);
  903. return $groupUsers;
  904. }
  905. $search = $this->access->escapeFilterPart($search, true);
  906. $isMemberUid =
  907. ($this->ldapGroupMemberAssocAttr === 'memberuid' ||
  908. $this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress');
  909. //we need to apply the search filter
  910. //alternatives that need to be checked:
  911. //a) get all users by search filter and array_intersect them
  912. //b) a, but only when less than 1k 10k ?k users like it is
  913. //c) put all DNs|uids in a LDAP filter, combine with the search string
  914. // and let it count.
  915. //For now this is not important, because the only use of this method
  916. //does not supply a search string
  917. $groupUsers = [];
  918. foreach ($members as $member) {
  919. if ($isMemberUid) {
  920. if ($this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress') {
  921. //we get email addresses and need to convert them to uids
  922. $parts = explode('@', $member);
  923. $member = $parts[0];
  924. }
  925. //we got uids, need to get their DNs to 'translate' them to user names
  926. $filter = $this->access->combineFilterWithAnd([
  927. str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
  928. $this->access->getFilterPartForUserSearch($search)
  929. ]);
  930. $ldap_users = $this->access->fetchListOfUsers($filter, ['dn'], 1);
  931. if (count($ldap_users) < 1) {
  932. continue;
  933. }
  934. $groupUsers[] = $this->access->dn2username($ldap_users[0]);
  935. } else {
  936. //we need to apply the search filter now
  937. if (!$this->access->readAttribute($member,
  938. $this->access->connection->ldapUserDisplayName,
  939. $this->access->getFilterPartForUserSearch($search))) {
  940. continue;
  941. }
  942. // dn2username will also check if the users belong to the allowed base
  943. if ($ncGroupId = $this->access->dn2username($member)) {
  944. $groupUsers[] = $ncGroupId;
  945. }
  946. }
  947. }
  948. //and get users that have the group as primary
  949. $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
  950. return count($groupUsers) + $primaryUsers;
  951. }
  952. /**
  953. * get a list of all groups using a paged search
  954. *
  955. * @param string $search
  956. * @param int $limit
  957. * @param int $offset
  958. * @return array with group names
  959. *
  960. * Returns a list with all groups
  961. * Uses a paged search if available to override a
  962. * server side search limit.
  963. * (active directory has a limit of 1000 by default)
  964. * @throws Exception
  965. */
  966. public function getGroups($search = '', $limit = -1, $offset = 0) {
  967. if (!$this->enabled) {
  968. return [];
  969. }
  970. $search = $this->access->escapeFilterPart($search, true);
  971. $cacheKey = 'getGroups-' . $search . '-' . $limit . '-' . $offset;
  972. //Check cache before driving unnecessary searches
  973. $ldap_groups = $this->access->connection->getFromCache($cacheKey);
  974. if (!is_null($ldap_groups)) {
  975. return $ldap_groups;
  976. }
  977. // if we'd pass -1 to LDAP search, we'd end up in a Protocol
  978. // error. With a limit of 0, we get 0 results. So we pass null.
  979. if ($limit <= 0) {
  980. $limit = null;
  981. }
  982. $filter = $this->access->combineFilterWithAnd([
  983. $this->access->connection->ldapGroupFilter,
  984. $this->access->getFilterPartForGroupSearch($search)
  985. ]);
  986. $ldap_groups = $this->access->fetchListOfGroups($filter,
  987. [$this->access->connection->ldapGroupDisplayName, 'dn'],
  988. $limit,
  989. $offset);
  990. $ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
  991. $this->access->connection->writeToCache($cacheKey, $ldap_groups);
  992. return $ldap_groups;
  993. }
  994. /**
  995. * check if a group exists
  996. *
  997. * @param string $gid
  998. * @return bool
  999. * @throws ServerNotAvailableException
  1000. */
  1001. public function groupExists($gid) {
  1002. $groupExists = $this->access->connection->getFromCache('groupExists' . $gid);
  1003. if (!is_null($groupExists)) {
  1004. return (bool)$groupExists;
  1005. }
  1006. //getting dn, if false the group does not exist. If dn, it may be mapped
  1007. //only, requires more checking.
  1008. $dn = $this->access->groupname2dn($gid);
  1009. if (!$dn) {
  1010. $this->access->connection->writeToCache('groupExists' . $gid, false);
  1011. return false;
  1012. }
  1013. if (!$this->access->isDNPartOfBase($dn, $this->access->connection->ldapBaseGroups)) {
  1014. $this->access->connection->writeToCache('groupExists' . $gid, false);
  1015. return false;
  1016. }
  1017. //if group really still exists, we will be able to read its objectClass
  1018. if (!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapGroupFilter))) {
  1019. $this->access->connection->writeToCache('groupExists' . $gid, false);
  1020. return false;
  1021. }
  1022. $this->access->connection->writeToCache('groupExists' . $gid, true);
  1023. return true;
  1024. }
  1025. /**
  1026. * @template T
  1027. * @param array<array-key, T> $listOfGroups
  1028. * @return array<array-key, T>
  1029. * @throws ServerNotAvailableException
  1030. * @throws Exception
  1031. */
  1032. protected function filterValidGroups(array $listOfGroups): array {
  1033. $validGroupDNs = [];
  1034. foreach ($listOfGroups as $key => $item) {
  1035. $dn = is_string($item) ? $item : $item['dn'][0];
  1036. if (is_array($item) && !isset($item[$this->access->connection->ldapGroupDisplayName][0])) {
  1037. continue;
  1038. }
  1039. $name = $item[$this->access->connection->ldapGroupDisplayName][0] ?? null;
  1040. $gid = $this->access->dn2groupname($dn, $name);
  1041. if (!$gid) {
  1042. continue;
  1043. }
  1044. if ($this->groupExists($gid)) {
  1045. $validGroupDNs[$key] = $item;
  1046. }
  1047. }
  1048. return $validGroupDNs;
  1049. }
  1050. /**
  1051. * Check if backend implements actions
  1052. *
  1053. * @param int $actions bitwise-or'ed actions
  1054. * @return boolean
  1055. *
  1056. * Returns the supported actions as int to be
  1057. * compared with GroupInterface::CREATE_GROUP etc.
  1058. */
  1059. public function implementsActions($actions): bool {
  1060. return (bool)((GroupInterface::COUNT_USERS |
  1061. GroupInterface::DELETE_GROUP |
  1062. $this->groupPluginManager->getImplementedActions()) & $actions);
  1063. }
  1064. /**
  1065. * Return access for LDAP interaction.
  1066. *
  1067. * @return Access instance of Access for LDAP interaction
  1068. */
  1069. public function getLDAPAccess($gid) {
  1070. return $this->access;
  1071. }
  1072. /**
  1073. * create a group
  1074. *
  1075. * @param string $gid
  1076. * @return bool
  1077. * @throws Exception
  1078. * @throws ServerNotAvailableException
  1079. */
  1080. public function createGroup($gid) {
  1081. if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) {
  1082. if ($dn = $this->groupPluginManager->createGroup($gid)) {
  1083. //updates group mapping
  1084. $uuid = $this->access->getUUID($dn, false);
  1085. if (is_string($uuid)) {
  1086. $this->access->mapAndAnnounceIfApplicable(
  1087. $this->access->getGroupMapper(),
  1088. $dn,
  1089. $gid,
  1090. $uuid,
  1091. false
  1092. );
  1093. $this->access->cacheGroupExists($gid);
  1094. }
  1095. }
  1096. return $dn != null;
  1097. }
  1098. throw new Exception('Could not create group in LDAP backend.');
  1099. }
  1100. /**
  1101. * delete a group
  1102. *
  1103. * @param string $gid gid of the group to delete
  1104. * @throws Exception
  1105. */
  1106. public function deleteGroup(string $gid): bool {
  1107. if ($this->groupPluginManager->canDeleteGroup()) {
  1108. if ($ret = $this->groupPluginManager->deleteGroup($gid)) {
  1109. // Delete group in nextcloud internal db
  1110. $this->access->getGroupMapper()->unmap($gid);
  1111. $this->access->connection->writeToCache("groupExists" . $gid, false);
  1112. }
  1113. return $ret;
  1114. }
  1115. // Getting dn, if false the group is not mapped
  1116. $dn = $this->access->groupname2dn($gid);
  1117. if (!$dn) {
  1118. throw new Exception('Could not delete unknown group '.$gid.' in LDAP backend.');
  1119. }
  1120. if (!$this->groupExists($gid)) {
  1121. // The group does not exist in the LDAP, remove the mapping
  1122. $this->access->getGroupMapper()->unmap($gid);
  1123. $this->access->connection->writeToCache("groupExists" . $gid, false);
  1124. return true;
  1125. }
  1126. throw new Exception('Could not delete existing group '.$gid.' in LDAP backend.');
  1127. }
  1128. /**
  1129. * Add a user to a group
  1130. *
  1131. * @param string $uid Name of the user to add to group
  1132. * @param string $gid Name of the group in which add the user
  1133. * @return bool
  1134. * @throws Exception
  1135. */
  1136. public function addToGroup($uid, $gid) {
  1137. if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) {
  1138. if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) {
  1139. $this->access->connection->clearCache();
  1140. unset($this->cachedGroupMembers[$gid]);
  1141. }
  1142. return $ret;
  1143. }
  1144. throw new Exception('Could not add user to group in LDAP backend.');
  1145. }
  1146. /**
  1147. * Removes a user from a group
  1148. *
  1149. * @param string $uid Name of the user to remove from group
  1150. * @param string $gid Name of the group from which remove the user
  1151. * @return bool
  1152. * @throws Exception
  1153. */
  1154. public function removeFromGroup($uid, $gid) {
  1155. if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) {
  1156. if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) {
  1157. $this->access->connection->clearCache();
  1158. unset($this->cachedGroupMembers[$gid]);
  1159. }
  1160. return $ret;
  1161. }
  1162. throw new Exception('Could not remove user from group in LDAP backend.');
  1163. }
  1164. /**
  1165. * Gets group details
  1166. *
  1167. * @param string $gid Name of the group
  1168. * @return array|false
  1169. * @throws Exception
  1170. */
  1171. public function getGroupDetails($gid) {
  1172. if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) {
  1173. return $this->groupPluginManager->getGroupDetails($gid);
  1174. }
  1175. throw new Exception('Could not get group details in LDAP backend.');
  1176. }
  1177. /**
  1178. * Return LDAP connection resource from a cloned connection.
  1179. * The cloned connection needs to be closed manually.
  1180. * of the current access.
  1181. *
  1182. * @param string $gid
  1183. * @return resource|\LDAP\Connection The LDAP connection
  1184. * @throws ServerNotAvailableException
  1185. */
  1186. public function getNewLDAPConnection($gid) {
  1187. $connection = clone $this->access->getConnection();
  1188. return $connection->getConnectionResource();
  1189. }
  1190. /**
  1191. * @throws ServerNotAvailableException
  1192. */
  1193. public function getDisplayName(string $gid): string {
  1194. if ($this->groupPluginManager instanceof IGetDisplayNameBackend) {
  1195. return $this->groupPluginManager->getDisplayName($gid);
  1196. }
  1197. $cacheKey = 'group_getDisplayName' . $gid;
  1198. if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
  1199. return $displayName;
  1200. }
  1201. $displayName = $this->access->readAttribute(
  1202. $this->access->groupname2dn($gid),
  1203. $this->access->connection->ldapGroupDisplayName);
  1204. if (($displayName !== false) && (count($displayName) > 0)) {
  1205. $displayName = $displayName[0];
  1206. } else {
  1207. $displayName = '';
  1208. }
  1209. $this->access->connection->writeToCache($cacheKey, $displayName);
  1210. return $displayName;
  1211. }
  1212. }