1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426 |
- <?php
- namespace OCA\User_LDAP;
- use Exception;
- use OC\ServerNotAvailableException;
- use OCA\User_LDAP\User\OfflineUser;
- use OCP\Cache\CappedMemoryCache;
- use OCP\Group\Backend\ABackend;
- use OCP\Group\Backend\IDeleteGroupBackend;
- use OCP\Group\Backend\IGetDisplayNameBackend;
- use OCP\Group\Backend\IIsAdminBackend;
- use OCP\GroupInterface;
- use OCP\IConfig;
- use OCP\IUserManager;
- use OCP\Server;
- use Psr\Log\LoggerInterface;
- use function json_decode;
- class Group_LDAP extends ABackend implements GroupInterface, IGroupLDAP, IGetDisplayNameBackend, IDeleteGroupBackend, IIsAdminBackend {
- protected bool $enabled = false;
-
- protected CappedMemoryCache $cachedGroupMembers;
-
- protected CappedMemoryCache $cachedGroupsByMember;
-
- protected CappedMemoryCache $cachedNestedGroups;
- protected GroupPluginManager $groupPluginManager;
- protected LoggerInterface $logger;
- protected Access $access;
-
- protected string $ldapGroupMemberAssocAttr;
- private IConfig $config;
- private IUserManager $ncUserManager;
- public function __construct(
- Access $access,
- GroupPluginManager $groupPluginManager,
- IConfig $config,
- IUserManager $ncUserManager
- ) {
- $this->access = $access;
- $filter = $this->access->connection->ldapGroupFilter;
- $gAssoc = $this->access->connection->ldapGroupMemberAssocAttr;
- if (!empty($filter) && !empty($gAssoc)) {
- $this->enabled = true;
- }
- $this->cachedGroupMembers = new CappedMemoryCache();
- $this->cachedGroupsByMember = new CappedMemoryCache();
- $this->cachedNestedGroups = new CappedMemoryCache();
- $this->groupPluginManager = $groupPluginManager;
- $this->logger = Server::get(LoggerInterface::class);
- $this->ldapGroupMemberAssocAttr = strtolower((string)$gAssoc);
- $this->config = $config;
- $this->ncUserManager = $ncUserManager;
- }
-
- public function inGroup($uid, $gid): bool {
- if (!$this->enabled) {
- return false;
- }
- $cacheKey = 'inGroup' . $uid . ':' . $gid;
- $inGroup = $this->access->connection->getFromCache($cacheKey);
- if (!is_null($inGroup)) {
- return (bool)$inGroup;
- }
- $userDN = $this->access->username2dn($uid);
- if (isset($this->cachedGroupMembers[$gid])) {
- return in_array($userDN, $this->cachedGroupMembers[$gid]);
- }
- $cacheKeyMembers = 'inGroup-members:' . $gid;
- $members = $this->access->connection->getFromCache($cacheKeyMembers);
- if (!is_null($members)) {
- $this->cachedGroupMembers[$gid] = $members;
- $isInGroup = in_array($userDN, $members, true);
- $this->access->connection->writeToCache($cacheKey, $isInGroup);
- return $isInGroup;
- }
- $groupDN = $this->access->groupname2dn($gid);
-
- if (!$groupDN || !$userDN) {
- $this->access->connection->writeToCache($cacheKey, false);
- return false;
- }
-
- if ($gid === $this->getUserPrimaryGroup($userDN)) {
- $this->access->connection->writeToCache($cacheKey, true);
- return true;
- }
-
- $members = $this->_groupMembers($groupDN);
-
- switch ($this->ldapGroupMemberAssocAttr) {
- case 'memberuid':
- case 'zimbramailforwardingaddress':
- $requestAttributes = $this->access->userManager->getAttributes(true);
- $users = [];
- $filterParts = [];
- $bytes = 0;
- foreach ($members as $mid) {
- if ($this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress') {
- $parts = explode('@', $mid);
- $mid = $parts[0];
- }
- $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
- $filterParts[] = $filter;
- $bytes += strlen($filter);
- if ($bytes >= 9000000) {
-
-
-
- $filter = $this->access->combineFilterWithOr($filterParts);
- $search = $this->access->fetchListOfUsers($filter, $requestAttributes, count($filterParts));
- $bytes = 0;
- $filterParts = [];
- $users = array_merge($users, $search);
- }
- }
- if (count($filterParts) > 0) {
-
- $filter = $this->access->combineFilterWithOr($filterParts);
- $search = $this->access->fetchListOfUsers($filter, $requestAttributes, count($filterParts));
- $users = array_merge($users, $search);
- }
-
- $dns = [];
- foreach ($users as $record) {
- $dns[$record['dn'][0]] = 1;
- }
- $members = array_keys($dns);
- break;
- }
- if (count($members) === 0) {
- $this->access->connection->writeToCache($cacheKey, false);
- return false;
- }
- $isInGroup = in_array($userDN, $members);
- $this->access->connection->writeToCache($cacheKey, $isInGroup);
- $this->access->connection->writeToCache($cacheKeyMembers, $members);
- $this->cachedGroupMembers[$gid] = $members;
- return $isInGroup;
- }
-
- public function getDynamicGroupMembers(string $dnGroup): array {
- $dynamicGroupMemberURL = strtolower((string)$this->access->connection->ldapDynamicGroupMemberURL);
- if (empty($dynamicGroupMemberURL)) {
- return [];
- }
- $dynamicMembers = [];
- $memberURLs = $this->access->readAttribute(
- $dnGroup,
- $dynamicGroupMemberURL,
- $this->access->connection->ldapGroupFilter
- );
- if ($memberURLs !== false) {
-
-
-
- $pos = strpos($memberURLs[0], '(');
- if ($pos !== false) {
- $memberUrlFilter = substr($memberURLs[0], $pos);
- $foundMembers = $this->access->searchUsers($memberUrlFilter, ['dn']);
- $dynamicMembers = [];
- foreach ($foundMembers as $value) {
- $dynamicMembers[$value['dn'][0]] = 1;
- }
- } else {
- $this->logger->debug('No search filter found on member url of group {dn}',
- [
- 'app' => 'user_ldap',
- 'dn' => $dnGroup,
- ]
- );
- }
- }
- return $dynamicMembers;
- }
-
- private function _groupMembers(string $dnGroup, array $seen = [], bool &$recursive = false): array {
- if (isset($seen[$dnGroup])) {
- $recursive = true;
- return [];
- }
- $seen[$dnGroup] = true;
-
- $cacheKey = '_groupMembers' . $dnGroup;
- $groupMembers = $this->access->connection->getFromCache($cacheKey);
- if ($groupMembers !== null) {
- return $groupMembers;
- }
- if ($this->access->connection->ldapNestedGroups
- && $this->access->connection->useMemberOfToDetectMembership
- && $this->access->connection->hasMemberOfFilterSupport
- && $this->access->connection->ldapMatchingRuleInChainState !== Configuration::LDAP_SERVER_FEATURE_UNAVAILABLE
- ) {
- $attemptedLdapMatchingRuleInChain = true;
-
- $filter = $this->access->combineFilterWithAnd([
- $this->access->connection->ldapUserFilter,
- $this->access->connection->ldapUserDisplayName . '=*',
- 'memberof:1.2.840.113556.1.4.1941:=' . $dnGroup
- ]);
- $memberRecords = $this->access->fetchListOfUsers(
- $filter,
- $this->access->userManager->getAttributes(true)
- );
- $result = array_reduce($memberRecords, function ($carry, $record) {
- $carry[] = $record['dn'][0];
- return $carry;
- }, []);
- if ($this->access->connection->ldapMatchingRuleInChainState === Configuration::LDAP_SERVER_FEATURE_AVAILABLE) {
- $this->access->connection->writeToCache($cacheKey, $result);
- return $result;
- } elseif (!empty($memberRecords)) {
- $this->access->connection->ldapMatchingRuleInChainState = Configuration::LDAP_SERVER_FEATURE_AVAILABLE;
- $this->access->connection->saveConfiguration();
- $this->access->connection->writeToCache($cacheKey, $result);
- return $result;
- }
-
- }
- $allMembers = [];
- $members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr);
- if (is_array($members)) {
- if ((int)$this->access->connection->ldapNestedGroups === 1) {
- while ($recordDn = array_shift($members)) {
- $nestedMembers = $this->_groupMembers($recordDn, $seen, $recursive);
- if (!empty($nestedMembers)) {
-
- $members = array_merge($members, $nestedMembers);
- } else {
-
- $allMembers[] = $recordDn;
- }
- }
- } else {
- $allMembers = $members;
- }
- }
- $allMembers += $this->getDynamicGroupMembers($dnGroup);
- $allMembers = array_unique($allMembers);
-
- $index = array_search($dnGroup, $allMembers, true);
- if ($index !== false) {
- unset($allMembers[$index]);
- }
- if (!$recursive) {
- $this->access->connection->writeToCache($cacheKey, $allMembers);
- }
- if (isset($attemptedLdapMatchingRuleInChain)
- && $this->access->connection->ldapMatchingRuleInChainState === Configuration::LDAP_SERVER_FEATURE_UNKNOWN
- && !empty($allMembers)
- ) {
- $this->access->connection->ldapMatchingRuleInChainState = Configuration::LDAP_SERVER_FEATURE_UNAVAILABLE;
- $this->access->connection->saveConfiguration();
- }
- return $allMembers;
- }
-
- private function _getGroupDNsFromMemberOf(string $dn, array &$seen = []): array {
- if (isset($seen[$dn])) {
- return [];
- }
- $seen[$dn] = true;
- if (isset($this->cachedNestedGroups[$dn])) {
- return $this->cachedNestedGroups[$dn];
- }
- $allGroups = [];
- $groups = $this->access->readAttribute($dn, 'memberOf');
- if (is_array($groups)) {
- if ((int)$this->access->connection->ldapNestedGroups === 1) {
- while ($recordDn = array_shift($groups)) {
- $nestedParents = $this->_getGroupDNsFromMemberOf($recordDn, $seen);
- $groups = array_merge($groups, $nestedParents);
- $allGroups[] = $recordDn;
- }
- } else {
- $allGroups = $groups;
- }
- }
-
- $this->cachedNestedGroups[$dn] = $allGroups;
- return $this->filterValidGroups($allGroups);
- }
-
- public function gidNumber2Name(string $gid, string $dn) {
- $cacheKey = 'gidNumberToName' . $gid;
- $groupName = $this->access->connection->getFromCache($cacheKey);
- if (!is_null($groupName) && isset($groupName)) {
- return $groupName;
- }
-
- $filter = $this->access->combineFilterWithAnd([
- $this->access->connection->ldapGroupFilter,
- 'objectClass=posixGroup',
- $this->access->connection->ldapGidNumber . '=' . $gid
- ]);
- return $this->getNameOfGroup($filter, $cacheKey) ?? false;
- }
-
- private function getNameOfGroup(string $filter, string $cacheKey) {
- $result = $this->access->searchGroups($filter, ['dn'], 1);
- if (empty($result)) {
- $this->access->connection->writeToCache($cacheKey, false);
- return null;
- }
- $dn = $result[0]['dn'][0];
-
-
-
- $name = $this->access->dn2groupname($dn);
- $this->access->connection->writeToCache($cacheKey, $name);
- return $name;
- }
-
- private function getEntryGidNumber(string $dn, string $attribute) {
- $value = $this->access->readAttribute($dn, $attribute);
- if (is_array($value) && !empty($value)) {
- return $value[0];
- }
- return false;
- }
-
- public function getGroupGidNumber(string $dn) {
- return $this->getEntryGidNumber($dn, 'gidNumber');
- }
-
- public function getUserGidNumber(string $dn) {
- $gidNumber = false;
- if ($this->access->connection->hasGidNumber) {
-
- $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
- if ($gidNumber === false) {
- $this->access->connection->hasGidNumber = false;
- }
- }
- return $gidNumber;
- }
-
- private function prepareFilterForUsersHasGidNumber(string $groupDN, string $search = ''): string {
- $groupID = $this->getGroupGidNumber($groupDN);
- if ($groupID === false) {
- throw new Exception('Not a valid group');
- }
- $filterParts = [];
- $filterParts[] = $this->access->getFilterForUserCount();
- if ($search !== '') {
- $filterParts[] = $this->access->getFilterPartForUserSearch($search);
- }
- $filterParts[] = $this->access->connection->ldapGidNumber . '=' . $groupID;
- return $this->access->combineFilterWithAnd($filterParts);
- }
-
- public function getUsersInGidNumber(
- string $groupDN,
- string $search = '',
- ?int $limit = -1,
- ?int $offset = 0
- ): array {
- try {
- $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
- $users = $this->access->fetchListOfUsers(
- $filter,
- $this->access->userManager->getAttributes(true),
- $limit,
- $offset
- );
- return $this->access->nextcloudUserNames($users);
- } catch (ServerNotAvailableException $e) {
- throw $e;
- } catch (Exception $e) {
- return [];
- }
- }
-
- public function getUserGroupByGid(string $dn) {
- $groupID = $this->getUserGidNumber($dn);
- if ($groupID !== false) {
- $groupName = $this->gidNumber2Name($groupID, $dn);
- if ($groupName !== false) {
- return $groupName;
- }
- }
- return false;
- }
-
- public function primaryGroupID2Name(string $gid, string $dn) {
- $cacheKey = 'primaryGroupIDtoName_' . $gid;
- $groupName = $this->access->connection->getFromCache($cacheKey);
- if (!is_null($groupName)) {
- return $groupName;
- }
- $domainObjectSid = $this->access->getSID($dn);
- if ($domainObjectSid === false) {
- return false;
- }
-
- $filter = $this->access->combineFilterWithAnd([
- $this->access->connection->ldapGroupFilter,
- 'objectsid=' . $domainObjectSid . '-' . $gid
- ]);
- return $this->getNameOfGroup($filter, $cacheKey) ?? false;
- }
-
- private function getEntryGroupID(string $dn, string $attribute) {
- $value = $this->access->readAttribute($dn, $attribute);
- if (is_array($value) && !empty($value)) {
- return $value[0];
- }
- return false;
- }
-
- public function getGroupPrimaryGroupID(string $dn) {
- return $this->getEntryGroupID($dn, 'primaryGroupToken');
- }
-
- public function getUserPrimaryGroupIDs(string $dn) {
- $primaryGroupID = false;
- if ($this->access->connection->hasPrimaryGroups) {
- $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
- if ($primaryGroupID === false) {
- $this->access->connection->hasPrimaryGroups = false;
- }
- }
- return $primaryGroupID;
- }
-
- private function prepareFilterForUsersInPrimaryGroup(string $groupDN, string $search = ''): string {
- $groupID = $this->getGroupPrimaryGroupID($groupDN);
- if ($groupID === false) {
- throw new Exception('Not a valid group');
- }
- $filterParts = [];
- $filterParts[] = $this->access->getFilterForUserCount();
- if ($search !== '') {
- $filterParts[] = $this->access->getFilterPartForUserSearch($search);
- }
- $filterParts[] = 'primaryGroupID=' . $groupID;
- return $this->access->combineFilterWithAnd($filterParts);
- }
-
- public function getUsersInPrimaryGroup(
- string $groupDN,
- string $search = '',
- ?int $limit = -1,
- ?int $offset = 0
- ): array {
- try {
- $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
- $users = $this->access->fetchListOfUsers(
- $filter,
- $this->access->userManager->getAttributes(true),
- $limit,
- $offset
- );
- return $this->access->nextcloudUserNames($users);
- } catch (ServerNotAvailableException $e) {
- throw $e;
- } catch (Exception $e) {
- return [];
- }
- }
-
- public function countUsersInPrimaryGroup(
- string $groupDN,
- string $search = '',
- int $limit = -1,
- int $offset = 0
- ): int {
- try {
- $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
- $users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
- return (int)$users;
- } catch (ServerNotAvailableException $e) {
- throw $e;
- } catch (Exception $e) {
- return 0;
- }
- }
-
- public function getUserPrimaryGroup(string $dn) {
- $groupID = $this->getUserPrimaryGroupIDs($dn);
- if ($groupID !== false) {
- $groupName = $this->primaryGroupID2Name($groupID, $dn);
- if ($groupName !== false) {
- return $groupName;
- }
- }
- return false;
- }
- private function isUserOnLDAP(string $uid): bool {
-
- $ncUser = $this->ncUserManager->get($uid);
- if ($ncUser === null) {
- return false;
- }
- $backend = $ncUser->getBackend();
- if ($backend instanceof User_Proxy) {
-
- return $backend->userExistsOnLDAP($uid, true);
- }
- return false;
- }
- protected function getCachedGroupsForUserId(string $uid): array {
- $groupStr = $this->config->getUserValue($uid, 'user_ldap', 'cached-group-memberships-' . $this->access->connection->getConfigPrefix(), '[]');
- return json_decode($groupStr, true) ?? [];
- }
-
- public function getUserGroups($uid): array {
- if (!$this->enabled) {
- return [];
- }
- $ncUid = $uid;
- $cacheKey = 'getUserGroups' . $uid;
- $userGroups = $this->access->connection->getFromCache($cacheKey);
- if (!is_null($userGroups)) {
- return $userGroups;
- }
- $user = $this->access->userManager->get($uid);
- if ($user instanceof OfflineUser) {
-
-
- return $this->getCachedGroupsForUserId($uid);
- }
- $userDN = $this->access->username2dn($uid);
- if (!$userDN) {
- $this->access->connection->writeToCache($cacheKey, []);
- return [];
- }
- $groups = [];
- $primaryGroup = $this->getUserPrimaryGroup($userDN);
- $gidGroupName = $this->getUserGroupByGid($userDN);
- $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
- if (!empty($dynamicGroupMemberURL)) {
-
- $groupsToMatch = $this->access->fetchListOfGroups(
- $this->access->connection->ldapGroupFilter, ['dn', $dynamicGroupMemberURL]);
- foreach ($groupsToMatch as $dynamicGroup) {
- if (!isset($dynamicGroup[$dynamicGroupMemberURL][0])) {
- continue;
- }
- $pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
- if ($pos !== false) {
- $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0], $pos);
-
-
- $userMatch = $this->access->readAttribute(
- $userDN,
- $this->access->connection->ldapUserDisplayName,
- $memberUrlFilter
- );
- if ($userMatch !== false) {
-
- $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
- if (is_string($groupName)) {
-
-
- $groups[] = $groupName;
- }
- }
- } else {
- $this->logger->debug('No search filter found on member url of group {dn}',
- [
- 'app' => 'user_ldap',
- 'dn' => $dynamicGroup,
- ]
- );
- }
- }
- }
-
-
-
- if ((int)$this->access->connection->hasMemberOfFilterSupport === 1
- && (int)$this->access->connection->useMemberOfToDetectMembership === 1
- && $this->ldapGroupMemberAssocAttr !== 'memberuid'
- && $this->ldapGroupMemberAssocAttr !== 'zimbramailforwardingaddress') {
- $groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
- foreach ($groupDNs as $dn) {
- $groupName = $this->access->dn2groupname($dn);
- if (is_string($groupName)) {
-
-
- $groups[] = $groupName;
- }
- }
- } else {
-
- switch ($this->ldapGroupMemberAssocAttr) {
- case 'uniquemember':
- case 'member':
- $uid = $userDN;
- break;
- case 'memberuid':
- case 'zimbramailforwardingaddress':
- $result = $this->access->readAttribute($userDN, 'uid');
- if ($result === false) {
- $this->logger->debug('No uid attribute found for DN {dn} on {host}',
- [
- 'app' => 'user_ldap',
- 'dn' => $userDN,
- 'host' => $this->access->connection->ldapHost,
- ]
- );
- $uid = false;
- } else {
- $uid = $result[0];
- }
- break;
- default:
-
- $uid = $userDN;
- break;
- }
- if ($uid !== false) {
- $groupsByMember = array_values($this->getGroupsByMember($uid));
- $groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
- $groups = array_merge($groups, $groupsByMember);
- }
- }
- if ($primaryGroup !== false) {
- $groups[] = $primaryGroup;
- }
- if ($gidGroupName !== false) {
- $groups[] = $gidGroupName;
- }
- if (empty($groups) && !$this->isUserOnLDAP($ncUid)) {
-
-
-
- $groups = $this->getCachedGroupsForUserId($ncUid);
- $this->access->connection->writeToCache($cacheKey, $groups);
- return $groups;
- }
- $groups = array_values(array_unique($groups, SORT_LOCALE_STRING));
- $this->access->connection->writeToCache($cacheKey, $groups);
- $groupStr = \json_encode($groups);
- $this->config->setUserValue($ncUid, 'user_ldap', 'cached-group-memberships-' . $this->access->connection->getConfigPrefix(), $groupStr);
- return $groups;
- }
-
- private function getGroupsByMember(string $dn, array &$seen = []): array {
- if (isset($seen[$dn])) {
- return [];
- }
- $seen[$dn] = true;
- if (isset($this->cachedGroupsByMember[$dn])) {
- return $this->cachedGroupsByMember[$dn];
- }
- $filter = $this->access->connection->ldapGroupMemberAssocAttr . '=' . $dn;
- if ($this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress') {
-
- $filter .= '@*';
- }
- $nesting = (int)$this->access->connection->ldapNestedGroups;
- if ($nesting === 0) {
- $filter = $this->access->combineFilterWithAnd([$filter, $this->access->connection->ldapGroupFilter]);
- }
- $allGroups = [];
- $groups = $this->access->fetchListOfGroups($filter,
- [strtolower($this->access->connection->ldapGroupMemberAssocAttr), $this->access->connection->ldapGroupDisplayName, 'dn']);
- if ($nesting === 1) {
- while ($record = array_shift($groups)) {
-
- $nestedParents = $this->getGroupsByMember($record['dn'][0], $seen);
- $groups = array_merge($groups, $nestedParents);
- $allGroups[] = $record;
- }
- } else {
- $allGroups = $groups;
- }
- $visibleGroups = $this->filterValidGroups($allGroups);
- $this->cachedGroupsByMember[$dn] = $visibleGroups;
- return $visibleGroups;
- }
-
- public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
- if (!$this->enabled) {
- return [];
- }
- if (!$this->groupExists($gid)) {
- return [];
- }
- $search = $this->access->escapeFilterPart($search, true);
- $cacheKey = 'usersInGroup-' . $gid . '-' . $search . '-' . $limit . '-' . $offset;
-
- $groupUsers = $this->access->connection->getFromCache($cacheKey);
- if (!is_null($groupUsers)) {
- return $groupUsers;
- }
- if ($limit === -1) {
- $limit = null;
- }
-
- $groupUsers = $this->access->connection->getFromCache('usersInGroup-' . $gid . '-' . $search);
- if (!is_null($groupUsers)) {
- $groupUsers = array_slice($groupUsers, $offset, $limit);
- $this->access->connection->writeToCache($cacheKey, $groupUsers);
- return $groupUsers;
- }
- $groupDN = $this->access->groupname2dn($gid);
- if (!$groupDN) {
-
- $this->access->connection->writeToCache($cacheKey, []);
- return [];
- }
- $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
- $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
- $members = $this->_groupMembers($groupDN);
- if (!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
-
- $this->access->connection->writeToCache($cacheKey, []);
- return [];
- }
- $groupUsers = [];
- $attrs = $this->access->userManager->getAttributes(true);
- foreach ($members as $member) {
- switch ($this->ldapGroupMemberAssocAttr) {
-
- case 'zimbramailforwardingaddress':
-
- $parts = explode('@', $member);
- $member = $parts[0];
-
- case 'memberuid':
-
- $filter = $this->access->combineFilterWithAnd([
- str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
- $this->access->combineFilterWithAnd([
- $this->access->getFilterPartForUserSearch($search),
- $this->access->connection->ldapUserFilter
- ])
- ]);
- $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
- if (empty($ldap_users)) {
- break;
- }
- $uid = $this->access->dn2username($ldap_users[0]['dn'][0]);
- if (!$uid) {
- break;
- }
- $groupUsers[] = $uid;
- break;
- default:
-
- $uid = $this->access->dn2username($member);
- if (!$uid) {
- break;
- }
- $cacheKey = 'userExistsOnLDAP' . $uid;
- $userExists = $this->access->connection->getFromCache($cacheKey);
- if ($userExists === false) {
- break;
- }
- if ($userExists === null || $search !== '') {
- if (!$this->access->readAttribute($member,
- $this->access->connection->ldapUserDisplayName,
- $this->access->combineFilterWithAnd([
- $this->access->getFilterPartForUserSearch($search),
- $this->access->connection->ldapUserFilter
- ]))) {
- if ($search === '') {
- $this->access->connection->writeToCache($cacheKey, false);
- }
- break;
- }
- $this->access->connection->writeToCache($cacheKey, true);
- }
- $groupUsers[] = $uid;
- break;
- }
- }
- $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
- natsort($groupUsers);
- $this->access->connection->writeToCache('usersInGroup-' . $gid . '-' . $search, $groupUsers);
- $groupUsers = array_slice($groupUsers, $offset, $limit);
- $this->access->connection->writeToCache($cacheKey, $groupUsers);
- return $groupUsers;
- }
-
- public function countUsersInGroup($gid, $search = '') {
- if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) {
- return $this->groupPluginManager->countUsersInGroup($gid, $search);
- }
- $cacheKey = 'countUsersInGroup-' . $gid . '-' . $search;
- if (!$this->enabled || !$this->groupExists($gid)) {
- return false;
- }
- $groupUsers = $this->access->connection->getFromCache($cacheKey);
- if (!is_null($groupUsers)) {
- return $groupUsers;
- }
- $groupDN = $this->access->groupname2dn($gid);
- if (!$groupDN) {
-
- $this->access->connection->writeToCache($cacheKey, false);
- return false;
- }
- $members = $this->_groupMembers($groupDN);
- $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
- if (!$members && $primaryUserCount === 0) {
-
- $this->access->connection->writeToCache($cacheKey, false);
- return false;
- }
- if ($search === '') {
- $groupUsers = count($members) + $primaryUserCount;
- $this->access->connection->writeToCache($cacheKey, $groupUsers);
- return $groupUsers;
- }
- $search = $this->access->escapeFilterPart($search, true);
- $isMemberUid =
- ($this->ldapGroupMemberAssocAttr === 'memberuid' ||
- $this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress');
-
-
-
-
-
-
-
-
- $groupUsers = [];
- foreach ($members as $member) {
- if ($isMemberUid) {
- if ($this->ldapGroupMemberAssocAttr === 'zimbramailforwardingaddress') {
-
- $parts = explode('@', $member);
- $member = $parts[0];
- }
-
- $filter = $this->access->combineFilterWithAnd([
- str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
- $this->access->getFilterPartForUserSearch($search)
- ]);
- $ldap_users = $this->access->fetchListOfUsers($filter, ['dn'], 1);
- if (count($ldap_users) < 1) {
- continue;
- }
- $groupUsers[] = $this->access->dn2username($ldap_users[0]);
- } else {
-
- if (!$this->access->readAttribute($member,
- $this->access->connection->ldapUserDisplayName,
- $this->access->getFilterPartForUserSearch($search))) {
- continue;
- }
-
- if ($ncGroupId = $this->access->dn2username($member)) {
- $groupUsers[] = $ncGroupId;
- }
- }
- }
-
- $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
- return count($groupUsers) + $primaryUsers;
- }
-
- public function getGroups($search = '', $limit = -1, $offset = 0) {
- if (!$this->enabled) {
- return [];
- }
- $search = $this->access->escapeFilterPart($search, true);
- $cacheKey = 'getGroups-' . $search . '-' . $limit . '-' . $offset;
-
- $ldap_groups = $this->access->connection->getFromCache($cacheKey);
- if (!is_null($ldap_groups)) {
- return $ldap_groups;
- }
-
-
- if ($limit <= 0) {
- $limit = null;
- }
- $filter = $this->access->combineFilterWithAnd([
- $this->access->connection->ldapGroupFilter,
- $this->access->getFilterPartForGroupSearch($search)
- ]);
- $ldap_groups = $this->access->fetchListOfGroups($filter,
- [$this->access->connection->ldapGroupDisplayName, 'dn'],
- $limit,
- $offset);
- $ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
- $this->access->connection->writeToCache($cacheKey, $ldap_groups);
- return $ldap_groups;
- }
-
- public function groupExists($gid) {
- return $this->groupExistsOnLDAP($gid, false);
- }
-
- public function groupExistsOnLDAP(string $gid, bool $ignoreCache = false): bool {
- $cacheKey = 'groupExists' . $gid;
- if (!$ignoreCache) {
- $groupExists = $this->access->connection->getFromCache($cacheKey);
- if (!is_null($groupExists)) {
- return (bool)$groupExists;
- }
- }
-
-
- $dn = $this->access->groupname2dn($gid);
- if (!$dn) {
- $this->access->connection->writeToCache($cacheKey, false);
- return false;
- }
- if (!$this->access->isDNPartOfBase($dn, $this->access->connection->ldapBaseGroups)) {
- $this->access->connection->writeToCache($cacheKey, false);
- return false;
- }
-
- if (!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapGroupFilter))) {
- $this->access->connection->writeToCache($cacheKey, false);
- return false;
- }
- $this->access->connection->writeToCache($cacheKey, true);
- return true;
- }
-
- protected function filterValidGroups(array $listOfGroups): array {
- $validGroupDNs = [];
- foreach ($listOfGroups as $key => $item) {
- $dn = is_string($item) ? $item : $item['dn'][0];
- if (is_array($item) && !isset($item[$this->access->connection->ldapGroupDisplayName][0])) {
- continue;
- }
- $name = $item[$this->access->connection->ldapGroupDisplayName][0] ?? null;
- $gid = $this->access->dn2groupname($dn, $name);
- if (!$gid) {
- continue;
- }
- if ($this->groupExists($gid)) {
- $validGroupDNs[$key] = $item;
- }
- }
- return $validGroupDNs;
- }
-
- public function implementsActions($actions): bool {
- return (bool)((GroupInterface::COUNT_USERS |
- GroupInterface::DELETE_GROUP |
- GroupInterface::IS_ADMIN |
- $this->groupPluginManager->getImplementedActions()) & $actions);
- }
-
- public function getLDAPAccess($gid) {
- return $this->access;
- }
-
- public function createGroup($gid) {
- if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) {
- if ($dn = $this->groupPluginManager->createGroup($gid)) {
-
- $uuid = $this->access->getUUID($dn, false);
- if (is_string($uuid)) {
- $this->access->mapAndAnnounceIfApplicable(
- $this->access->getGroupMapper(),
- $dn,
- $gid,
- $uuid,
- false
- );
- $this->access->cacheGroupExists($gid);
- }
- }
- return $dn != null;
- }
- throw new Exception('Could not create group in LDAP backend.');
- }
-
- public function deleteGroup(string $gid): bool {
- if ($this->groupPluginManager->canDeleteGroup()) {
- if ($ret = $this->groupPluginManager->deleteGroup($gid)) {
-
- $this->access->getGroupMapper()->unmap($gid);
- $this->access->connection->writeToCache("groupExists" . $gid, false);
- }
- return $ret;
- }
-
- $dn = $this->access->groupname2dn($gid);
- if (!$dn) {
- throw new Exception('Could not delete unknown group '.$gid.' in LDAP backend.');
- }
- if (!$this->groupExists($gid)) {
-
- $this->access->getGroupMapper()->unmap($gid);
- $this->access->connection->writeToCache("groupExists" . $gid, false);
- return true;
- }
- throw new Exception('Could not delete existing group '.$gid.' in LDAP backend.');
- }
-
- public function addToGroup($uid, $gid) {
- if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) {
- if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) {
- $this->access->connection->clearCache();
- unset($this->cachedGroupMembers[$gid]);
- }
- return $ret;
- }
- throw new Exception('Could not add user to group in LDAP backend.');
- }
-
- public function removeFromGroup($uid, $gid) {
- if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) {
- if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) {
- $this->access->connection->clearCache();
- unset($this->cachedGroupMembers[$gid]);
- }
- return $ret;
- }
- throw new Exception('Could not remove user from group in LDAP backend.');
- }
-
- public function getGroupDetails($gid) {
- if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) {
- return $this->groupPluginManager->getGroupDetails($gid);
- }
- throw new Exception('Could not get group details in LDAP backend.');
- }
-
- public function getNewLDAPConnection($gid): \LDAP\Connection {
- $connection = clone $this->access->getConnection();
- return $connection->getConnectionResource();
- }
-
- public function getDisplayName(string $gid): string {
- if ($this->groupPluginManager instanceof IGetDisplayNameBackend) {
- return $this->groupPluginManager->getDisplayName($gid);
- }
- $cacheKey = 'group_getDisplayName' . $gid;
- if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
- return $displayName;
- }
- $displayName = $this->access->readAttribute(
- $this->access->groupname2dn($gid),
- $this->access->connection->ldapGroupDisplayName);
- if (($displayName !== false) && (count($displayName) > 0)) {
- $displayName = $displayName[0];
- } else {
- $displayName = '';
- }
- $this->access->connection->writeToCache($cacheKey, $displayName);
- return $displayName;
- }
-
- public function dn2GroupName(string $dn): string|false {
- return $this->access->dn2groupname($dn);
- }
- public function addRelationshipToCaches(string $uid, ?string $dnUser, string $gid): void {
- $dnGroup = $this->access->groupname2dn($gid);
- $dnUser ??= $this->access->username2dn($uid);
- if ($dnUser === false || $dnGroup === false) {
- return;
- }
- if (isset($this->cachedGroupMembers[$gid])) {
- $this->cachedGroupMembers[$gid] = array_merge($this->cachedGroupMembers[$gid], [$dnUser]);
- }
- unset($this->cachedGroupsByMember[$dnUser]);
- unset($this->cachedNestedGroups[$gid]);
- $cacheKey = 'inGroup' . $uid . ':' . $gid;
- $this->access->connection->writeToCache($cacheKey, true);
- $cacheKeyMembers = 'inGroup-members:' . $gid;
- if (!is_null($data = $this->access->connection->getFromCache($cacheKeyMembers))) {
- $this->access->connection->writeToCache($cacheKeyMembers, array_merge($data, [$dnUser]));
- }
- $cacheKey = '_groupMembers' . $dnGroup;
- if (!is_null($data = $this->access->connection->getFromCache($cacheKey))) {
- $this->access->connection->writeToCache($cacheKey, array_merge($data, [$dnUser]));
- }
- $cacheKey = 'getUserGroups' . $uid;
- if (!is_null($data = $this->access->connection->getFromCache($cacheKey))) {
- $this->access->connection->writeToCache($cacheKey, array_merge($data, [$gid]));
- }
-
-
-
-
- }
-
- public function isAdmin(string $uid): bool {
- if (!$this->enabled) {
- return false;
- }
- $ldapAdminGroup = $this->access->connection->ldapAdminGroup;
- if ($ldapAdminGroup === '') {
- return false;
- }
- return $this->inGroup($uid, $ldapAdminGroup);
- }
- }
|