Group_LDAP.php 39 KB

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