Group_LDAP.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358
  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. return $this->groupExistsOnLDAP($gid, false);
  1003. }
  1004. /**
  1005. * Check if a group exists
  1006. *
  1007. * @throws ServerNotAvailableException
  1008. */
  1009. public function groupExistsOnLDAP(string $gid, bool $ignoreCache = false): bool {
  1010. $cacheKey = 'groupExists' . $gid;
  1011. if (!$ignoreCache) {
  1012. $groupExists = $this->access->connection->getFromCache($cacheKey);
  1013. if (!is_null($groupExists)) {
  1014. return (bool)$groupExists;
  1015. }
  1016. }
  1017. //getting dn, if false the group does not exist. If dn, it may be mapped
  1018. //only, requires more checking.
  1019. $dn = $this->access->groupname2dn($gid);
  1020. if (!$dn) {
  1021. $this->access->connection->writeToCache($cacheKey, false);
  1022. return false;
  1023. }
  1024. if (!$this->access->isDNPartOfBase($dn, $this->access->connection->ldapBaseGroups)) {
  1025. $this->access->connection->writeToCache($cacheKey, false);
  1026. return false;
  1027. }
  1028. //if group really still exists, we will be able to read its objectClass
  1029. if (!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapGroupFilter))) {
  1030. $this->access->connection->writeToCache($cacheKey, false);
  1031. return false;
  1032. }
  1033. $this->access->connection->writeToCache($cacheKey, true);
  1034. return true;
  1035. }
  1036. /**
  1037. * @template T
  1038. * @param array<array-key, T> $listOfGroups
  1039. * @return array<array-key, T>
  1040. * @throws ServerNotAvailableException
  1041. * @throws Exception
  1042. */
  1043. protected function filterValidGroups(array $listOfGroups): array {
  1044. $validGroupDNs = [];
  1045. foreach ($listOfGroups as $key => $item) {
  1046. $dn = is_string($item) ? $item : $item['dn'][0];
  1047. if (is_array($item) && !isset($item[$this->access->connection->ldapGroupDisplayName][0])) {
  1048. continue;
  1049. }
  1050. $name = $item[$this->access->connection->ldapGroupDisplayName][0] ?? null;
  1051. $gid = $this->access->dn2groupname($dn, $name);
  1052. if (!$gid) {
  1053. continue;
  1054. }
  1055. if ($this->groupExists($gid)) {
  1056. $validGroupDNs[$key] = $item;
  1057. }
  1058. }
  1059. return $validGroupDNs;
  1060. }
  1061. /**
  1062. * Check if backend implements actions
  1063. *
  1064. * @param int $actions bitwise-or'ed actions
  1065. * @return boolean
  1066. *
  1067. * Returns the supported actions as int to be
  1068. * compared with GroupInterface::CREATE_GROUP etc.
  1069. */
  1070. public function implementsActions($actions): bool {
  1071. return (bool)((GroupInterface::COUNT_USERS |
  1072. GroupInterface::DELETE_GROUP |
  1073. $this->groupPluginManager->getImplementedActions()) & $actions);
  1074. }
  1075. /**
  1076. * Return access for LDAP interaction.
  1077. *
  1078. * @return Access instance of Access for LDAP interaction
  1079. */
  1080. public function getLDAPAccess($gid) {
  1081. return $this->access;
  1082. }
  1083. /**
  1084. * create a group
  1085. *
  1086. * @param string $gid
  1087. * @return bool
  1088. * @throws Exception
  1089. * @throws ServerNotAvailableException
  1090. */
  1091. public function createGroup($gid) {
  1092. if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) {
  1093. if ($dn = $this->groupPluginManager->createGroup($gid)) {
  1094. //updates group mapping
  1095. $uuid = $this->access->getUUID($dn, false);
  1096. if (is_string($uuid)) {
  1097. $this->access->mapAndAnnounceIfApplicable(
  1098. $this->access->getGroupMapper(),
  1099. $dn,
  1100. $gid,
  1101. $uuid,
  1102. false
  1103. );
  1104. $this->access->cacheGroupExists($gid);
  1105. }
  1106. }
  1107. return $dn != null;
  1108. }
  1109. throw new Exception('Could not create group in LDAP backend.');
  1110. }
  1111. /**
  1112. * delete a group
  1113. *
  1114. * @param string $gid gid of the group to delete
  1115. * @throws Exception
  1116. */
  1117. public function deleteGroup(string $gid): bool {
  1118. if ($this->groupPluginManager->canDeleteGroup()) {
  1119. if ($ret = $this->groupPluginManager->deleteGroup($gid)) {
  1120. // Delete group in nextcloud internal db
  1121. $this->access->getGroupMapper()->unmap($gid);
  1122. $this->access->connection->writeToCache("groupExists" . $gid, false);
  1123. }
  1124. return $ret;
  1125. }
  1126. // Getting dn, if false the group is not mapped
  1127. $dn = $this->access->groupname2dn($gid);
  1128. if (!$dn) {
  1129. throw new Exception('Could not delete unknown group '.$gid.' in LDAP backend.');
  1130. }
  1131. if (!$this->groupExists($gid)) {
  1132. // The group does not exist in the LDAP, remove the mapping
  1133. $this->access->getGroupMapper()->unmap($gid);
  1134. $this->access->connection->writeToCache("groupExists" . $gid, false);
  1135. return true;
  1136. }
  1137. throw new Exception('Could not delete existing group '.$gid.' in LDAP backend.');
  1138. }
  1139. /**
  1140. * Add a user to a group
  1141. *
  1142. * @param string $uid Name of the user to add to group
  1143. * @param string $gid Name of the group in which add the user
  1144. * @return bool
  1145. * @throws Exception
  1146. */
  1147. public function addToGroup($uid, $gid) {
  1148. if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) {
  1149. if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) {
  1150. $this->access->connection->clearCache();
  1151. unset($this->cachedGroupMembers[$gid]);
  1152. }
  1153. return $ret;
  1154. }
  1155. throw new Exception('Could not add user to group in LDAP backend.');
  1156. }
  1157. /**
  1158. * Removes a user from a group
  1159. *
  1160. * @param string $uid Name of the user to remove from group
  1161. * @param string $gid Name of the group from which remove the user
  1162. * @return bool
  1163. * @throws Exception
  1164. */
  1165. public function removeFromGroup($uid, $gid) {
  1166. if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) {
  1167. if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) {
  1168. $this->access->connection->clearCache();
  1169. unset($this->cachedGroupMembers[$gid]);
  1170. }
  1171. return $ret;
  1172. }
  1173. throw new Exception('Could not remove user from group in LDAP backend.');
  1174. }
  1175. /**
  1176. * Gets group details
  1177. *
  1178. * @param string $gid Name of the group
  1179. * @return array|false
  1180. * @throws Exception
  1181. */
  1182. public function getGroupDetails($gid) {
  1183. if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) {
  1184. return $this->groupPluginManager->getGroupDetails($gid);
  1185. }
  1186. throw new Exception('Could not get group details in LDAP backend.');
  1187. }
  1188. /**
  1189. * Return LDAP connection resource from a cloned connection.
  1190. * The cloned connection needs to be closed manually.
  1191. * of the current access.
  1192. *
  1193. * @param string $gid
  1194. * @return resource|\LDAP\Connection The LDAP connection
  1195. * @throws ServerNotAvailableException
  1196. */
  1197. public function getNewLDAPConnection($gid) {
  1198. $connection = clone $this->access->getConnection();
  1199. return $connection->getConnectionResource();
  1200. }
  1201. /**
  1202. * @throws ServerNotAvailableException
  1203. */
  1204. public function getDisplayName(string $gid): string {
  1205. if ($this->groupPluginManager instanceof IGetDisplayNameBackend) {
  1206. return $this->groupPluginManager->getDisplayName($gid);
  1207. }
  1208. $cacheKey = 'group_getDisplayName' . $gid;
  1209. if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
  1210. return $displayName;
  1211. }
  1212. $displayName = $this->access->readAttribute(
  1213. $this->access->groupname2dn($gid),
  1214. $this->access->connection->ldapGroupDisplayName);
  1215. if (($displayName !== false) && (count($displayName) > 0)) {
  1216. $displayName = $displayName[0];
  1217. } else {
  1218. $displayName = '';
  1219. }
  1220. $this->access->connection->writeToCache($cacheKey, $displayName);
  1221. return $displayName;
  1222. }
  1223. /**
  1224. * returns the groupname for the given LDAP DN, if available
  1225. */
  1226. public function dn2GroupName(string $dn): string|false {
  1227. return $this->access->dn2groupname($dn);
  1228. }
  1229. }