Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

Group_LDAP.php 41KB

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