1
0

Group_LDAP.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  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 Arthur Schiwon <blizzz@arthur-schiwon.de>
  10. * @author Bart Visscher <bartv@thisnet.nl>
  11. * @author Christopher Schäpers <kondou@ts.unde.re>
  12. * @author Frédéric Fortier <frederic.fortier@oronospolytechnique.com>
  13. * @author Joas Schilling <coding@schilljs.com>
  14. * @author Lukas Reschke <lukas@statuscode.ch>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Nicolas Grekas <nicolas.grekas@gmail.com>
  17. * @author Robin McCorkell <robin@mccorkell.me.uk>
  18. * @author Roeland Jago Douma <roeland@famdouma.nl>
  19. * @author Thomas Müller <thomas.mueller@tmit.eu>
  20. * @author Vincent Petry <pvince81@owncloud.com>
  21. *
  22. * @license AGPL-3.0
  23. *
  24. * This code is free software: you can redistribute it and/or modify
  25. * it under the terms of the GNU Affero General Public License, version 3,
  26. * as published by the Free Software Foundation.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU Affero General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Affero General Public License, version 3,
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>
  35. *
  36. */
  37. namespace OCA\User_LDAP;
  38. use OC\Cache\CappedMemoryCache;
  39. class Group_LDAP extends BackendUtility implements \OCP\GroupInterface {
  40. protected $enabled = false;
  41. /**
  42. * @var string[] $cachedGroupMembers array of users with gid as key
  43. */
  44. protected $cachedGroupMembers;
  45. /**
  46. * @var string[] $cachedGroupsByMember array of groups with uid as key
  47. */
  48. protected $cachedGroupsByMember;
  49. public function __construct(Access $access) {
  50. parent::__construct($access);
  51. $filter = $this->access->connection->ldapGroupFilter;
  52. $gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
  53. if(!empty($filter) && !empty($gassoc)) {
  54. $this->enabled = true;
  55. }
  56. $this->cachedGroupMembers = new CappedMemoryCache();
  57. $this->cachedGroupsByMember = new CappedMemoryCache();
  58. }
  59. /**
  60. * is user in group?
  61. * @param string $uid uid of the user
  62. * @param string $gid gid of the group
  63. * @return bool
  64. *
  65. * Checks whether the user is member of a group or not.
  66. */
  67. public function inGroup($uid, $gid) {
  68. if(!$this->enabled) {
  69. return false;
  70. }
  71. $cacheKey = 'inGroup'.$uid.':'.$gid;
  72. $inGroup = $this->access->connection->getFromCache($cacheKey);
  73. if(!is_null($inGroup)) {
  74. return (bool)$inGroup;
  75. }
  76. $userDN = $this->access->username2dn($uid);
  77. if(isset($this->cachedGroupMembers[$gid])) {
  78. $isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
  79. return $isInGroup;
  80. }
  81. $cacheKeyMembers = 'inGroup-members:'.$gid;
  82. $members = $this->access->connection->getFromCache($cacheKeyMembers);
  83. if(!is_null($members)) {
  84. $this->cachedGroupMembers[$gid] = $members;
  85. $isInGroup = in_array($userDN, $members);
  86. $this->access->connection->writeToCache($cacheKey, $isInGroup);
  87. return $isInGroup;
  88. }
  89. $groupDN = $this->access->groupname2dn($gid);
  90. // just in case
  91. if(!$groupDN || !$userDN) {
  92. $this->access->connection->writeToCache($cacheKey, false);
  93. return false;
  94. }
  95. //check primary group first
  96. if($gid === $this->getUserPrimaryGroup($userDN)) {
  97. $this->access->connection->writeToCache($cacheKey, true);
  98. return true;
  99. }
  100. //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
  101. $members = $this->_groupMembers($groupDN);
  102. $members = array_keys($members); // uids are returned as keys
  103. if(!is_array($members) || count($members) === 0) {
  104. $this->access->connection->writeToCache($cacheKey, false);
  105. return false;
  106. }
  107. //extra work if we don't get back user DNs
  108. if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
  109. $dns = array();
  110. $filterParts = array();
  111. $bytes = 0;
  112. foreach($members as $mid) {
  113. $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
  114. $filterParts[] = $filter;
  115. $bytes += strlen($filter);
  116. if($bytes >= 9000000) {
  117. // AD has a default input buffer of 10 MB, we do not want
  118. // to take even the chance to exceed it
  119. $filter = $this->access->combineFilterWithOr($filterParts);
  120. $bytes = 0;
  121. $filterParts = array();
  122. $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
  123. $dns = array_merge($dns, $users);
  124. }
  125. }
  126. if(count($filterParts) > 0) {
  127. $filter = $this->access->combineFilterWithOr($filterParts);
  128. $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
  129. $dns = array_merge($dns, $users);
  130. }
  131. $members = $dns;
  132. }
  133. $isInGroup = in_array($userDN, $members);
  134. $this->access->connection->writeToCache($cacheKey, $isInGroup);
  135. $this->access->connection->writeToCache($cacheKeyMembers, $members);
  136. $this->cachedGroupMembers[$gid] = $members;
  137. return $isInGroup;
  138. }
  139. /**
  140. * @param string $dnGroup
  141. * @return array
  142. *
  143. * For a group that has user membership defined by an LDAP search url attribute returns the users
  144. * that match the search url otherwise returns an empty array.
  145. */
  146. public function getDynamicGroupMembers($dnGroup) {
  147. $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
  148. if (empty($dynamicGroupMemberURL)) {
  149. return array();
  150. }
  151. $dynamicMembers = array();
  152. $memberURLs = $this->access->readAttribute(
  153. $dnGroup,
  154. $dynamicGroupMemberURL,
  155. $this->access->connection->ldapGroupFilter
  156. );
  157. if ($memberURLs !== false) {
  158. // this group has the 'memberURL' attribute so this is a dynamic group
  159. // example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice)
  160. // example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500))
  161. $pos = strpos($memberURLs[0], '(');
  162. if ($pos !== false) {
  163. $memberUrlFilter = substr($memberURLs[0], $pos);
  164. $foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
  165. $dynamicMembers = array();
  166. foreach($foundMembers as $value) {
  167. $dynamicMembers[$value['dn'][0]] = 1;
  168. }
  169. } else {
  170. \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
  171. 'of group ' . $dnGroup, \OCP\Util::DEBUG);
  172. }
  173. }
  174. return $dynamicMembers;
  175. }
  176. /**
  177. * @param string $dnGroup
  178. * @param array|null &$seen
  179. * @return array|mixed|null
  180. */
  181. private function _groupMembers($dnGroup, &$seen = null) {
  182. if ($seen === null) {
  183. $seen = array();
  184. }
  185. $allMembers = array();
  186. if (array_key_exists($dnGroup, $seen)) {
  187. // avoid loops
  188. return array();
  189. }
  190. // used extensively in cron job, caching makes sense for nested groups
  191. $cacheKey = '_groupMembers'.$dnGroup;
  192. $groupMembers = $this->access->connection->getFromCache($cacheKey);
  193. if(!is_null($groupMembers)) {
  194. return $groupMembers;
  195. }
  196. $seen[$dnGroup] = 1;
  197. $members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr,
  198. $this->access->connection->ldapGroupFilter);
  199. if (is_array($members)) {
  200. foreach ($members as $memberDN) {
  201. $allMembers[$memberDN] = 1;
  202. $nestedGroups = $this->access->connection->ldapNestedGroups;
  203. if (!empty($nestedGroups)) {
  204. $subMembers = $this->_groupMembers($memberDN, $seen);
  205. if ($subMembers) {
  206. $allMembers = array_merge($allMembers, $subMembers);
  207. }
  208. }
  209. }
  210. }
  211. $allMembers = array_merge($allMembers, $this->getDynamicGroupMembers($dnGroup));
  212. $this->access->connection->writeToCache($cacheKey, $allMembers);
  213. return $allMembers;
  214. }
  215. /**
  216. * @param string $DN
  217. * @param array|null &$seen
  218. * @return array
  219. */
  220. private function _getGroupDNsFromMemberOf($DN, &$seen = null) {
  221. if ($seen === null) {
  222. $seen = array();
  223. }
  224. if (array_key_exists($DN, $seen)) {
  225. // avoid loops
  226. return array();
  227. }
  228. $seen[$DN] = 1;
  229. $groups = $this->access->readAttribute($DN, 'memberOf');
  230. if (!is_array($groups)) {
  231. return array();
  232. }
  233. $groups = $this->access->groupsMatchFilter($groups);
  234. $allGroups = $groups;
  235. $nestedGroups = $this->access->connection->ldapNestedGroups;
  236. if (intval($nestedGroups) === 1) {
  237. foreach ($groups as $group) {
  238. $subGroups = $this->_getGroupDNsFromMemberOf($group, $seen);
  239. $allGroups = array_merge($allGroups, $subGroups);
  240. }
  241. }
  242. return $allGroups;
  243. }
  244. /**
  245. * translates a primary group ID into an ownCloud internal name
  246. * @param string $gid as given by primaryGroupID on AD
  247. * @param string $dn a DN that belongs to the same domain as the group
  248. * @return string|bool
  249. */
  250. public function primaryGroupID2Name($gid, $dn) {
  251. $cacheKey = 'primaryGroupIDtoName';
  252. $groupNames = $this->access->connection->getFromCache($cacheKey);
  253. if(!is_null($groupNames) && isset($groupNames[$gid])) {
  254. return $groupNames[$gid];
  255. }
  256. $domainObjectSid = $this->access->getSID($dn);
  257. if($domainObjectSid === false) {
  258. return false;
  259. }
  260. //we need to get the DN from LDAP
  261. $filter = $this->access->combineFilterWithAnd(array(
  262. $this->access->connection->ldapGroupFilter,
  263. 'objectsid=' . $domainObjectSid . '-' . $gid
  264. ));
  265. $result = $this->access->searchGroups($filter, array('dn'), 1);
  266. if(empty($result)) {
  267. return false;
  268. }
  269. $dn = $result[0]['dn'][0];
  270. //and now the group name
  271. //NOTE once we have separate ownCloud group IDs and group names we can
  272. //directly read the display name attribute instead of the DN
  273. $name = $this->access->dn2groupname($dn);
  274. $this->access->connection->writeToCache($cacheKey, $name);
  275. return $name;
  276. }
  277. /**
  278. * returns the entry's primary group ID
  279. * @param string $dn
  280. * @param string $attribute
  281. * @return string|bool
  282. */
  283. private function getEntryGroupID($dn, $attribute) {
  284. $value = $this->access->readAttribute($dn, $attribute);
  285. if(is_array($value) && !empty($value)) {
  286. return $value[0];
  287. }
  288. return false;
  289. }
  290. /**
  291. * returns the group's primary ID
  292. * @param string $dn
  293. * @return string|bool
  294. */
  295. public function getGroupPrimaryGroupID($dn) {
  296. return $this->getEntryGroupID($dn, 'primaryGroupToken');
  297. }
  298. /**
  299. * returns the user's primary group ID
  300. * @param string $dn
  301. * @return string|bool
  302. */
  303. public function getUserPrimaryGroupIDs($dn) {
  304. $primaryGroupID = false;
  305. if($this->access->connection->hasPrimaryGroups) {
  306. $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
  307. if($primaryGroupID === false) {
  308. $this->access->connection->hasPrimaryGroups = false;
  309. }
  310. }
  311. return $primaryGroupID;
  312. }
  313. /**
  314. * returns a filter for a "users in primary group" search or count operation
  315. *
  316. * @param string $groupDN
  317. * @param string $search
  318. * @return string
  319. * @throws \Exception
  320. */
  321. private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
  322. $groupID = $this->getGroupPrimaryGroupID($groupDN);
  323. if($groupID === false) {
  324. throw new \Exception('Not a valid group');
  325. }
  326. $filterParts = [];
  327. $filterParts[] = $this->access->getFilterForUserCount();
  328. if ($search !== '') {
  329. $filterParts[] = $this->access->getFilterPartForUserSearch($search);
  330. }
  331. $filterParts[] = 'primaryGroupID=' . $groupID;
  332. $filter = $this->access->combineFilterWithAnd($filterParts);
  333. return $filter;
  334. }
  335. /**
  336. * returns a list of users that have the given group as primary group
  337. *
  338. * @param string $groupDN
  339. * @param string $search
  340. * @param int $limit
  341. * @param int $offset
  342. * @return string[]
  343. */
  344. public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
  345. try {
  346. $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
  347. $users = $this->access->fetchListOfUsers(
  348. $filter,
  349. array($this->access->connection->ldapUserDisplayName, 'dn'),
  350. $limit,
  351. $offset
  352. );
  353. return $this->access->ownCloudUserNames($users);
  354. } catch (\Exception $e) {
  355. return array();
  356. }
  357. }
  358. /**
  359. * returns the number of users that have the given group as primary group
  360. *
  361. * @param string $groupDN
  362. * @param string $search
  363. * @param int $limit
  364. * @param int $offset
  365. * @return int
  366. */
  367. public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
  368. try {
  369. $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
  370. $users = $this->access->countUsers($filter, array('dn'), $limit, $offset);
  371. return (int)$users;
  372. } catch (\Exception $e) {
  373. return 0;
  374. }
  375. }
  376. /**
  377. * gets the primary group of a user
  378. * @param string $dn
  379. * @return string
  380. */
  381. public function getUserPrimaryGroup($dn) {
  382. $groupID = $this->getUserPrimaryGroupIDs($dn);
  383. if($groupID !== false) {
  384. $groupName = $this->primaryGroupID2Name($groupID, $dn);
  385. if($groupName !== false) {
  386. return $groupName;
  387. }
  388. }
  389. return false;
  390. }
  391. /**
  392. * Get all groups a user belongs to
  393. * @param string $uid Name of the user
  394. * @return array with group names
  395. *
  396. * This function fetches all groups a user belongs to. It does not check
  397. * if the user exists at all.
  398. *
  399. * This function includes groups based on dynamic group membership.
  400. */
  401. public function getUserGroups($uid) {
  402. if(!$this->enabled) {
  403. return array();
  404. }
  405. $cacheKey = 'getUserGroups'.$uid;
  406. $userGroups = $this->access->connection->getFromCache($cacheKey);
  407. if(!is_null($userGroups)) {
  408. return $userGroups;
  409. }
  410. $userDN = $this->access->username2dn($uid);
  411. if(!$userDN) {
  412. $this->access->connection->writeToCache($cacheKey, array());
  413. return array();
  414. }
  415. $groups = [];
  416. $primaryGroup = $this->getUserPrimaryGroup($userDN);
  417. $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
  418. if (!empty($dynamicGroupMemberURL)) {
  419. // look through dynamic groups to add them to the result array if needed
  420. $groupsToMatch = $this->access->fetchListOfGroups(
  421. $this->access->connection->ldapGroupFilter,array('dn',$dynamicGroupMemberURL));
  422. foreach($groupsToMatch as $dynamicGroup) {
  423. if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
  424. continue;
  425. }
  426. $pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
  427. if ($pos !== false) {
  428. $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
  429. // apply filter via ldap search to see if this user is in this
  430. // dynamic group
  431. $userMatch = $this->access->readAttribute(
  432. $userDN,
  433. $this->access->connection->ldapUserDisplayName,
  434. $memberUrlFilter
  435. );
  436. if ($userMatch !== false) {
  437. // match found so this user is in this group
  438. $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
  439. if(is_string($groupName)) {
  440. // be sure to never return false if the dn could not be
  441. // resolved to a name, for whatever reason.
  442. $groups[] = $groupName;
  443. }
  444. }
  445. } else {
  446. \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
  447. 'of group ' . print_r($dynamicGroup, true), \OCP\Util::DEBUG);
  448. }
  449. }
  450. }
  451. // if possible, read out membership via memberOf. It's far faster than
  452. // performing a search, which still is a fallback later.
  453. if(intval($this->access->connection->hasMemberOfFilterSupport) === 1
  454. && intval($this->access->connection->useMemberOfToDetectMembership) === 1
  455. ) {
  456. $groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
  457. if (is_array($groupDNs)) {
  458. foreach ($groupDNs as $dn) {
  459. $groupName = $this->access->dn2groupname($dn);
  460. if(is_string($groupName)) {
  461. // be sure to never return false if the dn could not be
  462. // resolved to a name, for whatever reason.
  463. $groups[] = $groupName;
  464. }
  465. }
  466. }
  467. if($primaryGroup !== false) {
  468. $groups[] = $primaryGroup;
  469. }
  470. $this->access->connection->writeToCache($cacheKey, $groups);
  471. return $groups;
  472. }
  473. //uniqueMember takes DN, memberuid the uid, so we need to distinguish
  474. if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
  475. || (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
  476. ) {
  477. $uid = $userDN;
  478. } else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
  479. $result = $this->access->readAttribute($userDN, 'uid');
  480. if ($result === false) {
  481. \OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
  482. $this->access->connection->ldapHost, \OCP\Util::DEBUG);
  483. }
  484. $uid = $result[0];
  485. } else {
  486. // just in case
  487. $uid = $userDN;
  488. }
  489. if(isset($this->cachedGroupsByMember[$uid])) {
  490. $groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
  491. } else {
  492. $groupsByMember = array_values($this->getGroupsByMember($uid));
  493. $groupsByMember = $this->access->ownCloudGroupNames($groupsByMember);
  494. $this->cachedGroupsByMember[$uid] = $groupsByMember;
  495. $groups = array_merge($groups, $groupsByMember);
  496. }
  497. if($primaryGroup !== false) {
  498. $groups[] = $primaryGroup;
  499. }
  500. $groups = array_unique($groups, SORT_LOCALE_STRING);
  501. $this->access->connection->writeToCache($cacheKey, $groups);
  502. return $groups;
  503. }
  504. /**
  505. * @param string $dn
  506. * @param array|null &$seen
  507. * @return array
  508. */
  509. private function getGroupsByMember($dn, &$seen = null) {
  510. if ($seen === null) {
  511. $seen = array();
  512. }
  513. $allGroups = array();
  514. if (array_key_exists($dn, $seen)) {
  515. // avoid loops
  516. return array();
  517. }
  518. $seen[$dn] = true;
  519. $filter = $this->access->combineFilterWithAnd(array(
  520. $this->access->connection->ldapGroupFilter,
  521. $this->access->connection->ldapGroupMemberAssocAttr.'='.$dn
  522. ));
  523. $groups = $this->access->fetchListOfGroups($filter,
  524. array($this->access->connection->ldapGroupDisplayName, 'dn'));
  525. if (is_array($groups)) {
  526. foreach ($groups as $groupobj) {
  527. $groupDN = $groupobj['dn'][0];
  528. $allGroups[$groupDN] = $groupobj;
  529. $nestedGroups = $this->access->connection->ldapNestedGroups;
  530. if (!empty($nestedGroups)) {
  531. $supergroups = $this->getGroupsByMember($groupDN, $seen);
  532. if (is_array($supergroups) && (count($supergroups)>0)) {
  533. $allGroups = array_merge($allGroups, $supergroups);
  534. }
  535. }
  536. }
  537. }
  538. return $allGroups;
  539. }
  540. /**
  541. * get a list of all users in a group
  542. *
  543. * @param string $gid
  544. * @param string $search
  545. * @param int $limit
  546. * @param int $offset
  547. * @return array with user ids
  548. */
  549. public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
  550. if(!$this->enabled) {
  551. return array();
  552. }
  553. if(!$this->groupExists($gid)) {
  554. return array();
  555. }
  556. $search = $this->access->escapeFilterPart($search, true);
  557. $cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
  558. // check for cache of the exact query
  559. $groupUsers = $this->access->connection->getFromCache($cacheKey);
  560. if(!is_null($groupUsers)) {
  561. return $groupUsers;
  562. }
  563. // check for cache of the query without limit and offset
  564. $groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
  565. if(!is_null($groupUsers)) {
  566. $groupUsers = array_slice($groupUsers, $offset, $limit);
  567. $this->access->connection->writeToCache($cacheKey, $groupUsers);
  568. return $groupUsers;
  569. }
  570. if($limit === -1) {
  571. $limit = null;
  572. }
  573. $groupDN = $this->access->groupname2dn($gid);
  574. if(!$groupDN) {
  575. // group couldn't be found, return empty resultset
  576. $this->access->connection->writeToCache($cacheKey, array());
  577. return array();
  578. }
  579. $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
  580. $members = array_keys($this->_groupMembers($groupDN));
  581. if(!$members && empty($primaryUsers)) {
  582. //in case users could not be retrieved, return empty result set
  583. $this->access->connection->writeToCache($cacheKey, array());
  584. return array();
  585. }
  586. $groupUsers = array();
  587. $isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
  588. $attrs = $this->access->userManager->getAttributes(true);
  589. foreach($members as $member) {
  590. if($isMemberUid) {
  591. //we got uids, need to get their DNs to 'translate' them to user names
  592. $filter = $this->access->combineFilterWithAnd(array(
  593. str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
  594. $this->access->getFilterPartForUserSearch($search)
  595. ));
  596. $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
  597. if(count($ldap_users) < 1) {
  598. continue;
  599. }
  600. $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
  601. } else {
  602. //we got DNs, check if we need to filter by search or we can give back all of them
  603. if ($search !== '') {
  604. if(!$this->access->readAttribute($member,
  605. $this->access->connection->ldapUserDisplayName,
  606. $this->access->getFilterPartForUserSearch($search))) {
  607. continue;
  608. }
  609. }
  610. // dn2username will also check if the users belong to the allowed base
  611. if($ocname = $this->access->dn2username($member)) {
  612. $groupUsers[] = $ocname;
  613. }
  614. }
  615. }
  616. $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers));
  617. natsort($groupUsers);
  618. $this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers);
  619. $groupUsers = array_slice($groupUsers, $offset, $limit);
  620. $this->access->connection->writeToCache($cacheKey, $groupUsers);
  621. return $groupUsers;
  622. }
  623. /**
  624. * returns the number of users in a group, who match the search term
  625. * @param string $gid the internal group name
  626. * @param string $search optional, a search string
  627. * @return int|bool
  628. */
  629. public function countUsersInGroup($gid, $search = '') {
  630. $cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
  631. if(!$this->enabled || !$this->groupExists($gid)) {
  632. return false;
  633. }
  634. $groupUsers = $this->access->connection->getFromCache($cacheKey);
  635. if(!is_null($groupUsers)) {
  636. return $groupUsers;
  637. }
  638. $groupDN = $this->access->groupname2dn($gid);
  639. if(!$groupDN) {
  640. // group couldn't be found, return empty result set
  641. $this->access->connection->writeToCache($cacheKey, false);
  642. return false;
  643. }
  644. $members = array_keys($this->_groupMembers($groupDN));
  645. $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
  646. if(!$members && $primaryUserCount === 0) {
  647. //in case users could not be retrieved, return empty result set
  648. $this->access->connection->writeToCache($cacheKey, false);
  649. return false;
  650. }
  651. if ($search === '') {
  652. $groupUsers = count($members) + $primaryUserCount;
  653. $this->access->connection->writeToCache($cacheKey, $groupUsers);
  654. return $groupUsers;
  655. }
  656. $search = $this->access->escapeFilterPart($search, true);
  657. $isMemberUid =
  658. (strtolower($this->access->connection->ldapGroupMemberAssocAttr)
  659. === 'memberuid');
  660. //we need to apply the search filter
  661. //alternatives that need to be checked:
  662. //a) get all users by search filter and array_intersect them
  663. //b) a, but only when less than 1k 10k ?k users like it is
  664. //c) put all DNs|uids in a LDAP filter, combine with the search string
  665. // and let it count.
  666. //For now this is not important, because the only use of this method
  667. //does not supply a search string
  668. $groupUsers = array();
  669. foreach($members as $member) {
  670. if($isMemberUid) {
  671. //we got uids, need to get their DNs to 'translate' them to user names
  672. $filter = $this->access->combineFilterWithAnd(array(
  673. str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
  674. $this->access->getFilterPartForUserSearch($search)
  675. ));
  676. $ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
  677. if(count($ldap_users) < 1) {
  678. continue;
  679. }
  680. $groupUsers[] = $this->access->dn2username($ldap_users[0]);
  681. } else {
  682. //we need to apply the search filter now
  683. if(!$this->access->readAttribute($member,
  684. $this->access->connection->ldapUserDisplayName,
  685. $this->access->getFilterPartForUserSearch($search))) {
  686. continue;
  687. }
  688. // dn2username will also check if the users belong to the allowed base
  689. if($ocname = $this->access->dn2username($member)) {
  690. $groupUsers[] = $ocname;
  691. }
  692. }
  693. }
  694. //and get users that have the group as primary
  695. $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
  696. return count($groupUsers) + $primaryUsers;
  697. }
  698. /**
  699. * get a list of all groups
  700. *
  701. * @param string $search
  702. * @param $limit
  703. * @param int $offset
  704. * @return array with group names
  705. *
  706. * Returns a list with all groups (used by getGroups)
  707. */
  708. protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
  709. if(!$this->enabled) {
  710. return array();
  711. }
  712. $cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
  713. //Check cache before driving unnecessary searches
  714. \OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, \OCP\Util::DEBUG);
  715. $ldap_groups = $this->access->connection->getFromCache($cacheKey);
  716. if(!is_null($ldap_groups)) {
  717. return $ldap_groups;
  718. }
  719. // if we'd pass -1 to LDAP search, we'd end up in a Protocol
  720. // error. With a limit of 0, we get 0 results. So we pass null.
  721. if($limit <= 0) {
  722. $limit = null;
  723. }
  724. $filter = $this->access->combineFilterWithAnd(array(
  725. $this->access->connection->ldapGroupFilter,
  726. $this->access->getFilterPartForGroupSearch($search)
  727. ));
  728. \OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, \OCP\Util::DEBUG);
  729. $ldap_groups = $this->access->fetchListOfGroups($filter,
  730. array($this->access->connection->ldapGroupDisplayName, 'dn'),
  731. $limit,
  732. $offset);
  733. $ldap_groups = $this->access->ownCloudGroupNames($ldap_groups);
  734. $this->access->connection->writeToCache($cacheKey, $ldap_groups);
  735. return $ldap_groups;
  736. }
  737. /**
  738. * get a list of all groups using a paged search
  739. *
  740. * @param string $search
  741. * @param int $limit
  742. * @param int $offset
  743. * @return array with group names
  744. *
  745. * Returns a list with all groups
  746. * Uses a paged search if available to override a
  747. * server side search limit.
  748. * (active directory has a limit of 1000 by default)
  749. */
  750. public function getGroups($search = '', $limit = -1, $offset = 0) {
  751. if(!$this->enabled) {
  752. return array();
  753. }
  754. $search = $this->access->escapeFilterPart($search, true);
  755. $pagingSize = intval($this->access->connection->ldapPagingSize);
  756. if (!$this->access->connection->hasPagedResultSupport || $pagingSize <= 0) {
  757. return $this->getGroupsChunk($search, $limit, $offset);
  758. }
  759. $maxGroups = 100000; // limit max results (just for safety reasons)
  760. if ($limit > -1) {
  761. $overallLimit = min($limit + $offset, $maxGroups);
  762. } else {
  763. $overallLimit = $maxGroups;
  764. }
  765. $chunkOffset = $offset;
  766. $allGroups = array();
  767. while ($chunkOffset < $overallLimit) {
  768. $chunkLimit = min($pagingSize, $overallLimit - $chunkOffset);
  769. $ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset);
  770. $nread = count($ldapGroups);
  771. \OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', \OCP\Util::DEBUG);
  772. if ($nread) {
  773. $allGroups = array_merge($allGroups, $ldapGroups);
  774. $chunkOffset += $nread;
  775. }
  776. if ($nread < $chunkLimit) {
  777. break;
  778. }
  779. }
  780. return $allGroups;
  781. }
  782. /**
  783. * @param string $group
  784. * @return bool
  785. */
  786. public function groupMatchesFilter($group) {
  787. return (strripos($group, $this->groupSearch) !== false);
  788. }
  789. /**
  790. * check if a group exists
  791. * @param string $gid
  792. * @return bool
  793. */
  794. public function groupExists($gid) {
  795. $groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
  796. if(!is_null($groupExists)) {
  797. return (bool)$groupExists;
  798. }
  799. //getting dn, if false the group does not exist. If dn, it may be mapped
  800. //only, requires more checking.
  801. $dn = $this->access->groupname2dn($gid);
  802. if(!$dn) {
  803. $this->access->connection->writeToCache('groupExists'.$gid, false);
  804. return false;
  805. }
  806. //if group really still exists, we will be able to read its objectclass
  807. if(!is_array($this->access->readAttribute($dn, ''))) {
  808. $this->access->connection->writeToCache('groupExists'.$gid, false);
  809. return false;
  810. }
  811. $this->access->connection->writeToCache('groupExists'.$gid, true);
  812. return true;
  813. }
  814. /**
  815. * Check if backend implements actions
  816. * @param int $actions bitwise-or'ed actions
  817. * @return boolean
  818. *
  819. * Returns the supported actions as int to be
  820. * compared with OC_USER_BACKEND_CREATE_USER etc.
  821. */
  822. public function implementsActions($actions) {
  823. return (bool)(\OC\Group\Backend::COUNT_USERS & $actions);
  824. }
  825. /**
  826. * Return access for LDAP interaction.
  827. * @return Access instance of Access for LDAP interaction
  828. */
  829. public function getLDAPAccess() {
  830. return $this->access;
  831. }
  832. }