You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Principal.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. * @copyright Copyright (c) 2018, Georg Ehrke
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Christoph Seitz <christoph.seitz@posteo.de>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  11. * @author Georg Ehrke <oc.list@georgehrke.com>
  12. * @author Jakob Sack <mail@jakobsack.de>
  13. * @author Julius Härtl <jus@bitgrid.net>
  14. * @author Lukas Reschke <lukas@statuscode.ch>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Thomas Müller <thomas.mueller@tmit.eu>
  18. * @author Vincent Petry <vincent@nextcloud.com>
  19. * @author Vinicius Cubas Brand <vinicius@eita.org.br>
  20. *
  21. * @license AGPL-3.0
  22. *
  23. * This code is free software: you can redistribute it and/or modify
  24. * it under the terms of the GNU Affero General Public License, version 3,
  25. * as published by the Free Software Foundation.
  26. *
  27. * This program is distributed in the hope that it will be useful,
  28. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  29. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  30. * GNU Affero General Public License for more details.
  31. *
  32. * You should have received a copy of the GNU Affero General Public License, version 3,
  33. * along with this program. If not, see <http://www.gnu.org/licenses/>
  34. *
  35. */
  36. namespace OCA\DAV\Connector\Sabre;
  37. use OCA\Circles\Exceptions\CircleDoesNotExistException;
  38. use OCA\DAV\CalDAV\Proxy\ProxyMapper;
  39. use OCA\DAV\Traits\PrincipalProxyTrait;
  40. use OCP\App\IAppManager;
  41. use OCP\AppFramework\QueryException;
  42. use OCP\Constants;
  43. use OCP\IConfig;
  44. use OCP\IGroupManager;
  45. use OCP\IUser;
  46. use OCP\IUserManager;
  47. use OCP\IUserSession;
  48. use OCP\Share\IManager as IShareManager;
  49. use Sabre\DAV\Exception;
  50. use Sabre\DAV\PropPatch;
  51. use Sabre\DAVACL\PrincipalBackend\BackendInterface;
  52. class Principal implements BackendInterface {
  53. /** @var IUserManager */
  54. private $userManager;
  55. /** @var IGroupManager */
  56. private $groupManager;
  57. /** @var IShareManager */
  58. private $shareManager;
  59. /** @var IUserSession */
  60. private $userSession;
  61. /** @var IAppManager */
  62. private $appManager;
  63. /** @var string */
  64. private $principalPrefix;
  65. /** @var bool */
  66. private $hasGroups;
  67. /** @var bool */
  68. private $hasCircles;
  69. /** @var ProxyMapper */
  70. private $proxyMapper;
  71. /** @var IConfig */
  72. private $config;
  73. /**
  74. * Principal constructor.
  75. *
  76. * @param IUserManager $userManager
  77. * @param IGroupManager $groupManager
  78. * @param IShareManager $shareManager
  79. * @param IUserSession $userSession
  80. * @param IAppManager $appManager
  81. * @param ProxyMapper $proxyMapper
  82. * @param IConfig $config
  83. * @param string $principalPrefix
  84. */
  85. public function __construct(IUserManager $userManager,
  86. IGroupManager $groupManager,
  87. IShareManager $shareManager,
  88. IUserSession $userSession,
  89. IAppManager $appManager,
  90. ProxyMapper $proxyMapper,
  91. IConfig $config,
  92. string $principalPrefix = 'principals/users/') {
  93. $this->userManager = $userManager;
  94. $this->groupManager = $groupManager;
  95. $this->shareManager = $shareManager;
  96. $this->userSession = $userSession;
  97. $this->appManager = $appManager;
  98. $this->principalPrefix = trim($principalPrefix, '/');
  99. $this->hasGroups = $this->hasCircles = ($principalPrefix === 'principals/users/');
  100. $this->proxyMapper = $proxyMapper;
  101. $this->config = $config;
  102. }
  103. use PrincipalProxyTrait {
  104. getGroupMembership as protected traitGetGroupMembership;
  105. }
  106. /**
  107. * Returns a list of principals based on a prefix.
  108. *
  109. * This prefix will often contain something like 'principals'. You are only
  110. * expected to return principals that are in this base path.
  111. *
  112. * You are expected to return at least a 'uri' for every user, you can
  113. * return any additional properties if you wish so. Common properties are:
  114. * {DAV:}displayname
  115. *
  116. * @param string $prefixPath
  117. * @return string[]
  118. */
  119. public function getPrincipalsByPrefix($prefixPath) {
  120. $principals = [];
  121. if ($prefixPath === $this->principalPrefix) {
  122. foreach ($this->userManager->search('') as $user) {
  123. $principals[] = $this->userToPrincipal($user);
  124. }
  125. }
  126. return $principals;
  127. }
  128. /**
  129. * Returns a specific principal, specified by it's path.
  130. * The returned structure should be the exact same as from
  131. * getPrincipalsByPrefix.
  132. *
  133. * @param string $path
  134. * @return array
  135. */
  136. public function getPrincipalByPath($path) {
  137. list($prefix, $name) = \Sabre\Uri\split($path);
  138. if ($name === 'calendar-proxy-write' || $name === 'calendar-proxy-read') {
  139. list($prefix2, $name2) = \Sabre\Uri\split($prefix);
  140. if ($prefix2 === $this->principalPrefix) {
  141. $user = $this->userManager->get($name2);
  142. if ($user !== null) {
  143. return [
  144. 'uri' => 'principals/users/' . $user->getUID() . '/' . $name,
  145. ];
  146. }
  147. return null;
  148. }
  149. }
  150. if ($prefix === $this->principalPrefix) {
  151. // Depending on where it is called, it may happen that this function
  152. // is called either with a urlencoded version of the name or with a non-urlencoded one.
  153. // The urldecode function replaces %## and +, both of which are forbidden in usernames.
  154. // Hence there can be no ambiguity here and it is safe to call urldecode on all usernames
  155. $user = $this->userManager->get(urldecode($name));
  156. if ($user !== null) {
  157. return $this->userToPrincipal($user);
  158. }
  159. } elseif ($prefix === 'principals/circles') {
  160. if ($this->userSession->getUser() !== null) {
  161. return $this->circleToPrincipal($name);
  162. }
  163. }
  164. return null;
  165. }
  166. /**
  167. * Returns the list of groups a principal is a member of
  168. *
  169. * @param string $principal
  170. * @param bool $needGroups
  171. * @return array
  172. * @throws Exception
  173. */
  174. public function getGroupMembership($principal, $needGroups = false) {
  175. list($prefix, $name) = \Sabre\Uri\split($principal);
  176. if ($prefix !== $this->principalPrefix) {
  177. return [];
  178. }
  179. $user = $this->userManager->get($name);
  180. if (!$user) {
  181. throw new Exception('Principal not found');
  182. }
  183. $groups = [];
  184. if ($this->hasGroups || $needGroups) {
  185. $userGroups = $this->groupManager->getUserGroups($user);
  186. foreach ($userGroups as $userGroup) {
  187. $groups[] = 'principals/groups/' . urlencode($userGroup->getGID());
  188. }
  189. }
  190. $groups = array_unique(array_merge(
  191. $groups,
  192. $this->traitGetGroupMembership($principal, $needGroups)
  193. ));
  194. return $groups;
  195. }
  196. /**
  197. * @param string $path
  198. * @param PropPatch $propPatch
  199. * @return int
  200. */
  201. public function updatePrincipal($path, PropPatch $propPatch) {
  202. return 0;
  203. }
  204. /**
  205. * Search user principals
  206. *
  207. * @param array $searchProperties
  208. * @param string $test
  209. * @return array
  210. */
  211. protected function searchUserPrincipals(array $searchProperties, $test = 'allof') {
  212. $results = [];
  213. // If sharing is disabled, return the empty array
  214. $shareAPIEnabled = $this->shareManager->shareApiEnabled();
  215. if (!$shareAPIEnabled) {
  216. return [];
  217. }
  218. $allowEnumeration = $this->shareManager->allowEnumeration();
  219. $limitEnumeration = $this->shareManager->limitEnumerationToGroups();
  220. // If sharing is restricted to group members only,
  221. // return only members that have groups in common
  222. $restrictGroups = false;
  223. if ($this->shareManager->shareWithGroupMembersOnly()) {
  224. $user = $this->userSession->getUser();
  225. if (!$user) {
  226. return [];
  227. }
  228. $restrictGroups = $this->groupManager->getUserGroupIds($user);
  229. }
  230. $currentUserGroups = [];
  231. if ($limitEnumeration) {
  232. $currentUser = $this->userSession->getUser();
  233. if ($currentUser) {
  234. $currentUserGroups = $this->groupManager->getUserGroupIds($currentUser);
  235. }
  236. }
  237. $searchLimit = $this->config->getSystemValueInt('sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT);
  238. if ($searchLimit <= 0) {
  239. $searchLimit = null;
  240. }
  241. foreach ($searchProperties as $prop => $value) {
  242. switch ($prop) {
  243. case '{http://sabredav.org/ns}email-address':
  244. $users = $this->userManager->getByEmail($value);
  245. if (!$allowEnumeration) {
  246. $users = \array_filter($users, static function (IUser $user) use ($value) {
  247. return $user->getEMailAddress() === $value;
  248. });
  249. }
  250. if ($limitEnumeration) {
  251. $users = \array_filter($users, function (IUser $user) use ($currentUserGroups, $value) {
  252. return !empty(array_intersect(
  253. $this->groupManager->getUserGroupIds($user),
  254. $currentUserGroups
  255. )) || $user->getEMailAddress() === $value;
  256. });
  257. }
  258. $results[] = array_reduce($users, function (array $carry, IUser $user) use ($restrictGroups) {
  259. // is sharing restricted to groups only?
  260. if ($restrictGroups !== false) {
  261. $userGroups = $this->groupManager->getUserGroupIds($user);
  262. if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
  263. return $carry;
  264. }
  265. }
  266. $carry[] = $this->principalPrefix . '/' . $user->getUID();
  267. return $carry;
  268. }, []);
  269. break;
  270. case '{DAV:}displayname':
  271. $users = $this->userManager->searchDisplayName($value, $searchLimit);
  272. if (!$allowEnumeration) {
  273. $users = \array_filter($users, static function (IUser $user) use ($value) {
  274. return $user->getDisplayName() === $value;
  275. });
  276. }
  277. if ($limitEnumeration) {
  278. $users = \array_filter($users, function (IUser $user) use ($currentUserGroups, $value) {
  279. return !empty(array_intersect(
  280. $this->groupManager->getUserGroupIds($user),
  281. $currentUserGroups
  282. )) || $user->getDisplayName() === $value;
  283. });
  284. }
  285. $results[] = array_reduce($users, function (array $carry, IUser $user) use ($restrictGroups) {
  286. // is sharing restricted to groups only?
  287. if ($restrictGroups !== false) {
  288. $userGroups = $this->groupManager->getUserGroupIds($user);
  289. if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
  290. return $carry;
  291. }
  292. }
  293. $carry[] = $this->principalPrefix . '/' . $user->getUID();
  294. return $carry;
  295. }, []);
  296. break;
  297. case '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set':
  298. // If you add support for more search properties that qualify as a user-address,
  299. // please also add them to the array below
  300. $results[] = $this->searchUserPrincipals([
  301. // In theory this should also search for principal:principals/users/...
  302. // but that's used internally only anyway and i don't know of any client querying that
  303. '{http://sabredav.org/ns}email-address' => $value,
  304. ], 'anyof');
  305. break;
  306. default:
  307. $results[] = [];
  308. break;
  309. }
  310. }
  311. // results is an array of arrays, so this is not the first search result
  312. // but the results of the first searchProperty
  313. if (count($results) === 1) {
  314. return $results[0];
  315. }
  316. switch ($test) {
  317. case 'anyof':
  318. return array_values(array_unique(array_merge(...$results)));
  319. case 'allof':
  320. default:
  321. return array_values(array_intersect(...$results));
  322. }
  323. }
  324. /**
  325. * @param string $prefixPath
  326. * @param array $searchProperties
  327. * @param string $test
  328. * @return array
  329. */
  330. public function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
  331. if (count($searchProperties) === 0) {
  332. return [];
  333. }
  334. switch ($prefixPath) {
  335. case 'principals/users':
  336. return $this->searchUserPrincipals($searchProperties, $test);
  337. default:
  338. return [];
  339. }
  340. }
  341. /**
  342. * @param string $uri
  343. * @param string $principalPrefix
  344. * @return string
  345. */
  346. public function findByUri($uri, $principalPrefix) {
  347. // If sharing is disabled, return the empty array
  348. $shareAPIEnabled = $this->shareManager->shareApiEnabled();
  349. if (!$shareAPIEnabled) {
  350. return null;
  351. }
  352. // If sharing is restricted to group members only,
  353. // return only members that have groups in common
  354. $restrictGroups = false;
  355. if ($this->shareManager->shareWithGroupMembersOnly()) {
  356. $user = $this->userSession->getUser();
  357. if (!$user) {
  358. return null;
  359. }
  360. $restrictGroups = $this->groupManager->getUserGroupIds($user);
  361. }
  362. if (strpos($uri, 'mailto:') === 0) {
  363. if ($principalPrefix === 'principals/users') {
  364. $users = $this->userManager->getByEmail(substr($uri, 7));
  365. if (count($users) !== 1) {
  366. return null;
  367. }
  368. $user = $users[0];
  369. if ($restrictGroups !== false) {
  370. $userGroups = $this->groupManager->getUserGroupIds($user);
  371. if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
  372. return null;
  373. }
  374. }
  375. return $this->principalPrefix . '/' . $user->getUID();
  376. }
  377. }
  378. if (substr($uri, 0, 10) === 'principal:') {
  379. $principal = substr($uri, 10);
  380. $principal = $this->getPrincipalByPath($principal);
  381. if ($principal !== null) {
  382. return $principal['uri'];
  383. }
  384. }
  385. return null;
  386. }
  387. /**
  388. * @param IUser $user
  389. * @return array
  390. */
  391. protected function userToPrincipal($user) {
  392. $userId = $user->getUID();
  393. $displayName = $user->getDisplayName();
  394. $principal = [
  395. 'uri' => $this->principalPrefix . '/' . $userId,
  396. '{DAV:}displayname' => is_null($displayName) ? $userId : $displayName,
  397. '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'INDIVIDUAL',
  398. ];
  399. $email = $user->getEMailAddress();
  400. if (!empty($email)) {
  401. $principal['{http://sabredav.org/ns}email-address'] = $email;
  402. }
  403. return $principal;
  404. }
  405. public function getPrincipalPrefix() {
  406. return $this->principalPrefix;
  407. }
  408. /**
  409. * @param string $circleUniqueId
  410. * @return array|null
  411. */
  412. protected function circleToPrincipal($circleUniqueId) {
  413. if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
  414. return null;
  415. }
  416. try {
  417. $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($circleUniqueId, true);
  418. } catch (QueryException $ex) {
  419. return null;
  420. } catch (CircleDoesNotExistException $ex) {
  421. return null;
  422. }
  423. if (!$circle) {
  424. return null;
  425. }
  426. $principal = [
  427. 'uri' => 'principals/circles/' . $circleUniqueId,
  428. '{DAV:}displayname' => $circle->getName(),
  429. ];
  430. return $principal;
  431. }
  432. /**
  433. * Returns the list of circles a principal is a member of
  434. *
  435. * @param string $principal
  436. * @return array
  437. * @throws Exception
  438. * @throws \OCP\AppFramework\QueryException
  439. * @suppress PhanUndeclaredClassMethod
  440. */
  441. public function getCircleMembership($principal):array {
  442. if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
  443. return [];
  444. }
  445. list($prefix, $name) = \Sabre\Uri\split($principal);
  446. if ($this->hasCircles && $prefix === $this->principalPrefix) {
  447. $user = $this->userManager->get($name);
  448. if (!$user) {
  449. throw new Exception('Principal not found');
  450. }
  451. $circles = \OCA\Circles\Api\v1\Circles::joinedCircles($name, true);
  452. $circles = array_map(function ($circle) {
  453. /** @var \OCA\Circles\Model\Circle $circle */
  454. return 'principals/circles/' . urlencode($circle->getUniqueId());
  455. }, $circles);
  456. return $circles;
  457. }
  458. return [];
  459. }
  460. }