Principal.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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 Joas Schilling <coding@schilljs.com>
  14. * @author Julius Härtl <jus@bitgrid.net>
  15. * @author Lukas Reschke <lukas@statuscode.ch>
  16. * @author Maxence Lange <maxence@artificial-owl.com>
  17. * @author Morris Jobke <hey@morrisjobke.de>
  18. * @author Roeland Jago Douma <roeland@famdouma.nl>
  19. * @author Thomas Müller <thomas.mueller@tmit.eu>
  20. * @author Vincent Petry <vincent@nextcloud.com>
  21. * @author Vinicius Cubas Brand <vinicius@eita.org.br>
  22. *
  23. * @license AGPL-3.0
  24. *
  25. * This code is free software: you can redistribute it and/or modify
  26. * it under the terms of the GNU Affero General Public License, version 3,
  27. * as published by the Free Software Foundation.
  28. *
  29. * This program is distributed in the hope that it will be useful,
  30. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  31. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  32. * GNU Affero General Public License for more details.
  33. *
  34. * You should have received a copy of the GNU Affero General Public License, version 3,
  35. * along with this program. If not, see <http://www.gnu.org/licenses/>
  36. *
  37. */
  38. namespace OCA\DAV\Connector\Sabre;
  39. use OC\KnownUser\KnownUserService;
  40. use OCA\Circles\Exceptions\CircleNotFoundException;
  41. use OCA\DAV\CalDAV\Proxy\ProxyMapper;
  42. use OCA\DAV\Traits\PrincipalProxyTrait;
  43. use OCP\Accounts\IAccountManager;
  44. use OCP\Accounts\IAccountProperty;
  45. use OCP\Accounts\PropertyDoesNotExistException;
  46. use OCP\App\IAppManager;
  47. use OCP\AppFramework\QueryException;
  48. use OCP\Constants;
  49. use OCP\IConfig;
  50. use OCP\IGroup;
  51. use OCP\IGroupManager;
  52. use OCP\IUser;
  53. use OCP\IUserManager;
  54. use OCP\IUserSession;
  55. use OCP\L10N\IFactory;
  56. use OCP\Share\IManager as IShareManager;
  57. use Sabre\DAV\Exception;
  58. use Sabre\DAV\PropPatch;
  59. use Sabre\DAVACL\PrincipalBackend\BackendInterface;
  60. class Principal implements BackendInterface {
  61. /** @var IUserManager */
  62. private $userManager;
  63. /** @var IGroupManager */
  64. private $groupManager;
  65. /** @var IAccountManager */
  66. private $accountManager;
  67. /** @var IShareManager */
  68. private $shareManager;
  69. /** @var IUserSession */
  70. private $userSession;
  71. /** @var IAppManager */
  72. private $appManager;
  73. /** @var string */
  74. private $principalPrefix;
  75. /** @var bool */
  76. private $hasGroups;
  77. /** @var bool */
  78. private $hasCircles;
  79. /** @var ProxyMapper */
  80. private $proxyMapper;
  81. /** @var KnownUserService */
  82. private $knownUserService;
  83. /** @var IConfig */
  84. private $config;
  85. /** @var IFactory */
  86. private $languageFactory;
  87. public function __construct(IUserManager $userManager,
  88. IGroupManager $groupManager,
  89. IAccountManager $accountManager,
  90. IShareManager $shareManager,
  91. IUserSession $userSession,
  92. IAppManager $appManager,
  93. ProxyMapper $proxyMapper,
  94. KnownUserService $knownUserService,
  95. IConfig $config,
  96. IFactory $languageFactory,
  97. string $principalPrefix = 'principals/users/') {
  98. $this->userManager = $userManager;
  99. $this->groupManager = $groupManager;
  100. $this->accountManager = $accountManager;
  101. $this->shareManager = $shareManager;
  102. $this->userSession = $userSession;
  103. $this->appManager = $appManager;
  104. $this->principalPrefix = trim($principalPrefix, '/');
  105. $this->hasGroups = $this->hasCircles = ($principalPrefix === 'principals/users/');
  106. $this->proxyMapper = $proxyMapper;
  107. $this->knownUserService = $knownUserService;
  108. $this->config = $config;
  109. $this->languageFactory = $languageFactory;
  110. }
  111. use PrincipalProxyTrait {
  112. getGroupMembership as protected traitGetGroupMembership;
  113. }
  114. /**
  115. * Returns a list of principals based on a prefix.
  116. *
  117. * This prefix will often contain something like 'principals'. You are only
  118. * expected to return principals that are in this base path.
  119. *
  120. * You are expected to return at least a 'uri' for every user, you can
  121. * return any additional properties if you wish so. Common properties are:
  122. * {DAV:}displayname
  123. *
  124. * @param string $prefixPath
  125. * @return string[]
  126. */
  127. public function getPrincipalsByPrefix($prefixPath) {
  128. $principals = [];
  129. if ($prefixPath === $this->principalPrefix) {
  130. foreach ($this->userManager->search('') as $user) {
  131. $principals[] = $this->userToPrincipal($user);
  132. }
  133. }
  134. return $principals;
  135. }
  136. /**
  137. * Returns a specific principal, specified by it's path.
  138. * The returned structure should be the exact same as from
  139. * getPrincipalsByPrefix.
  140. *
  141. * @param string $path
  142. * @return array
  143. */
  144. public function getPrincipalByPath($path) {
  145. [$prefix, $name] = \Sabre\Uri\split($path);
  146. $decodedName = urldecode($name);
  147. if ($name === 'calendar-proxy-write' || $name === 'calendar-proxy-read') {
  148. [$prefix2, $name2] = \Sabre\Uri\split($prefix);
  149. if ($prefix2 === $this->principalPrefix) {
  150. $user = $this->userManager->get($name2);
  151. if ($user !== null) {
  152. return [
  153. 'uri' => 'principals/users/' . $user->getUID() . '/' . $name,
  154. ];
  155. }
  156. return null;
  157. }
  158. }
  159. if ($prefix === $this->principalPrefix) {
  160. // Depending on where it is called, it may happen that this function
  161. // is called either with a urlencoded version of the name or with a non-urlencoded one.
  162. // The urldecode function replaces %## and +, both of which are forbidden in usernames.
  163. // Hence there can be no ambiguity here and it is safe to call urldecode on all usernames
  164. $user = $this->userManager->get($decodedName);
  165. if ($user !== null) {
  166. return $this->userToPrincipal($user);
  167. }
  168. } elseif ($prefix === 'principals/circles') {
  169. if ($this->userSession->getUser() !== null) {
  170. // At the time of writing - 2021-01-19 — a mixed state is possible.
  171. // The second condition can be removed when this is fixed.
  172. return $this->circleToPrincipal($decodedName)
  173. ?: $this->circleToPrincipal($name);
  174. }
  175. } elseif ($prefix === 'principals/groups') {
  176. // At the time of writing - 2021-01-19 — a mixed state is possible.
  177. // The second condition can be removed when this is fixed.
  178. $group = $this->groupManager->get($decodedName)
  179. ?: $this->groupManager->get($name);
  180. if ($group instanceof IGroup) {
  181. return [
  182. 'uri' => 'principals/groups/' . $name,
  183. '{DAV:}displayname' => $group->getDisplayName(),
  184. ];
  185. }
  186. }
  187. return null;
  188. }
  189. /**
  190. * Returns the list of groups a principal is a member of
  191. *
  192. * @param string $principal
  193. * @param bool $needGroups
  194. * @return array
  195. * @throws Exception
  196. */
  197. public function getGroupMembership($principal, $needGroups = false) {
  198. [$prefix, $name] = \Sabre\Uri\split($principal);
  199. if ($prefix !== $this->principalPrefix) {
  200. return [];
  201. }
  202. $user = $this->userManager->get($name);
  203. if (!$user) {
  204. throw new Exception('Principal not found');
  205. }
  206. $groups = [];
  207. if ($this->hasGroups || $needGroups) {
  208. $userGroups = $this->groupManager->getUserGroups($user);
  209. foreach ($userGroups as $userGroup) {
  210. $groups[] = 'principals/groups/' . urlencode($userGroup->getGID());
  211. }
  212. }
  213. $groups = array_unique(array_merge(
  214. $groups,
  215. $this->traitGetGroupMembership($principal, $needGroups)
  216. ));
  217. return $groups;
  218. }
  219. /**
  220. * @param string $path
  221. * @param PropPatch $propPatch
  222. * @return int
  223. */
  224. public function updatePrincipal($path, PropPatch $propPatch) {
  225. return 0;
  226. }
  227. /**
  228. * Search user principals
  229. *
  230. * @param array $searchProperties
  231. * @param string $test
  232. * @return array
  233. */
  234. protected function searchUserPrincipals(array $searchProperties, $test = 'allof') {
  235. $results = [];
  236. // If sharing is disabled, return the empty array
  237. $shareAPIEnabled = $this->shareManager->shareApiEnabled();
  238. if (!$shareAPIEnabled) {
  239. return [];
  240. }
  241. $allowEnumeration = $this->shareManager->allowEnumeration();
  242. $limitEnumerationGroup = $this->shareManager->limitEnumerationToGroups();
  243. $limitEnumerationPhone = $this->shareManager->limitEnumerationToPhone();
  244. $allowEnumerationFullMatch = $this->shareManager->allowEnumerationFullMatch();
  245. $ignoreSecondDisplayName = $this->shareManager->ignoreSecondDisplayName();
  246. $matchEmail = $this->shareManager->matchEmail();
  247. // If sharing is restricted to group members only,
  248. // return only members that have groups in common
  249. $restrictGroups = false;
  250. $currentUser = $this->userSession->getUser();
  251. if ($this->shareManager->shareWithGroupMembersOnly()) {
  252. if (!$currentUser instanceof IUser) {
  253. return [];
  254. }
  255. $restrictGroups = $this->groupManager->getUserGroupIds($currentUser);
  256. }
  257. $currentUserGroups = [];
  258. if ($limitEnumerationGroup) {
  259. if ($currentUser instanceof IUser) {
  260. $currentUserGroups = $this->groupManager->getUserGroupIds($currentUser);
  261. }
  262. }
  263. $searchLimit = $this->config->getSystemValueInt('sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT);
  264. if ($searchLimit <= 0) {
  265. $searchLimit = null;
  266. }
  267. foreach ($searchProperties as $prop => $value) {
  268. switch ($prop) {
  269. case '{http://sabredav.org/ns}email-address':
  270. if (!$allowEnumeration) {
  271. if ($allowEnumerationFullMatch && $matchEmail) {
  272. $users = $this->userManager->getByEmail($value);
  273. } else {
  274. $users = [];
  275. }
  276. } else {
  277. $users = $this->userManager->getByEmail($value);
  278. $users = \array_filter($users, function (IUser $user) use ($currentUser, $value, $limitEnumerationPhone, $limitEnumerationGroup, $allowEnumerationFullMatch, $currentUserGroups) {
  279. if ($allowEnumerationFullMatch && $user->getSystemEMailAddress() === $value) {
  280. return true;
  281. }
  282. if ($limitEnumerationPhone
  283. && $currentUser instanceof IUser
  284. && $this->knownUserService->isKnownToUser($currentUser->getUID(), $user->getUID())) {
  285. // Synced phonebook match
  286. return true;
  287. }
  288. if (!$limitEnumerationGroup) {
  289. // No limitation on enumeration, all allowed
  290. return true;
  291. }
  292. return !empty($currentUserGroups) && !empty(array_intersect(
  293. $this->groupManager->getUserGroupIds($user),
  294. $currentUserGroups
  295. ));
  296. });
  297. }
  298. $results[] = array_reduce($users, function (array $carry, IUser $user) use ($restrictGroups) {
  299. // is sharing restricted to groups only?
  300. if ($restrictGroups !== false) {
  301. $userGroups = $this->groupManager->getUserGroupIds($user);
  302. if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
  303. return $carry;
  304. }
  305. }
  306. $carry[] = $this->principalPrefix . '/' . $user->getUID();
  307. return $carry;
  308. }, []);
  309. break;
  310. case '{DAV:}displayname':
  311. if (!$allowEnumeration) {
  312. if ($allowEnumerationFullMatch) {
  313. $lowerSearch = strtolower($value);
  314. $users = $this->userManager->searchDisplayName($value, $searchLimit);
  315. $users = \array_filter($users, static function (IUser $user) use ($lowerSearch, $ignoreSecondDisplayName) {
  316. $lowerDisplayName = strtolower($user->getDisplayName());
  317. return $lowerDisplayName === $lowerSearch || ($ignoreSecondDisplayName && trim(preg_replace('/ \(.*\)$/', '', $lowerDisplayName)) === $lowerSearch);
  318. });
  319. } else {
  320. $users = [];
  321. }
  322. } else {
  323. $users = $this->userManager->searchDisplayName($value, $searchLimit);
  324. $users = \array_filter($users, function (IUser $user) use ($currentUser, $value, $limitEnumerationPhone, $limitEnumerationGroup, $allowEnumerationFullMatch, $currentUserGroups) {
  325. if ($allowEnumerationFullMatch && $user->getDisplayName() === $value) {
  326. return true;
  327. }
  328. if ($limitEnumerationPhone
  329. && $currentUser instanceof IUser
  330. && $this->knownUserService->isKnownToUser($currentUser->getUID(), $user->getUID())) {
  331. // Synced phonebook match
  332. return true;
  333. }
  334. if (!$limitEnumerationGroup) {
  335. // No limitation on enumeration, all allowed
  336. return true;
  337. }
  338. return !empty($currentUserGroups) && !empty(array_intersect(
  339. $this->groupManager->getUserGroupIds($user),
  340. $currentUserGroups
  341. ));
  342. });
  343. }
  344. $results[] = array_reduce($users, function (array $carry, IUser $user) use ($restrictGroups) {
  345. // is sharing restricted to groups only?
  346. if ($restrictGroups !== false) {
  347. $userGroups = $this->groupManager->getUserGroupIds($user);
  348. if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
  349. return $carry;
  350. }
  351. }
  352. $carry[] = $this->principalPrefix . '/' . $user->getUID();
  353. return $carry;
  354. }, []);
  355. break;
  356. case '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set':
  357. // If you add support for more search properties that qualify as a user-address,
  358. // please also add them to the array below
  359. $results[] = $this->searchUserPrincipals([
  360. // In theory this should also search for principal:principals/users/...
  361. // but that's used internally only anyway and i don't know of any client querying that
  362. '{http://sabredav.org/ns}email-address' => $value,
  363. ], 'anyof');
  364. break;
  365. default:
  366. $results[] = [];
  367. break;
  368. }
  369. }
  370. // results is an array of arrays, so this is not the first search result
  371. // but the results of the first searchProperty
  372. if (count($results) === 1) {
  373. return $results[0];
  374. }
  375. switch ($test) {
  376. case 'anyof':
  377. return array_values(array_unique(array_merge(...$results)));
  378. case 'allof':
  379. default:
  380. return array_values(array_intersect(...$results));
  381. }
  382. }
  383. /**
  384. * @param string $prefixPath
  385. * @param array $searchProperties
  386. * @param string $test
  387. * @return array
  388. */
  389. public function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
  390. if (count($searchProperties) === 0) {
  391. return [];
  392. }
  393. switch ($prefixPath) {
  394. case 'principals/users':
  395. return $this->searchUserPrincipals($searchProperties, $test);
  396. default:
  397. return [];
  398. }
  399. }
  400. /**
  401. * @param string $uri
  402. * @param string $principalPrefix
  403. * @return string
  404. */
  405. public function findByUri($uri, $principalPrefix) {
  406. // If sharing is disabled, return the empty array
  407. $shareAPIEnabled = $this->shareManager->shareApiEnabled();
  408. if (!$shareAPIEnabled) {
  409. return null;
  410. }
  411. // If sharing is restricted to group members only,
  412. // return only members that have groups in common
  413. $restrictGroups = false;
  414. if ($this->shareManager->shareWithGroupMembersOnly()) {
  415. $user = $this->userSession->getUser();
  416. if (!$user) {
  417. return null;
  418. }
  419. $restrictGroups = $this->groupManager->getUserGroupIds($user);
  420. }
  421. if (strpos($uri, 'mailto:') === 0) {
  422. if ($principalPrefix === 'principals/users') {
  423. $users = $this->userManager->getByEmail(substr($uri, 7));
  424. if (count($users) !== 1) {
  425. return null;
  426. }
  427. $user = $users[0];
  428. if ($restrictGroups !== false) {
  429. $userGroups = $this->groupManager->getUserGroupIds($user);
  430. if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
  431. return null;
  432. }
  433. }
  434. return $this->principalPrefix . '/' . $user->getUID();
  435. }
  436. }
  437. if (substr($uri, 0, 10) === 'principal:') {
  438. $principal = substr($uri, 10);
  439. $principal = $this->getPrincipalByPath($principal);
  440. if ($principal !== null) {
  441. return $principal['uri'];
  442. }
  443. }
  444. return null;
  445. }
  446. /**
  447. * @param IUser $user
  448. * @return array
  449. * @throws PropertyDoesNotExistException
  450. */
  451. protected function userToPrincipal($user) {
  452. $userId = $user->getUID();
  453. $displayName = $user->getDisplayName();
  454. $principal = [
  455. 'uri' => $this->principalPrefix . '/' . $userId,
  456. '{DAV:}displayname' => is_null($displayName) ? $userId : $displayName,
  457. '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'INDIVIDUAL',
  458. '{http://nextcloud.com/ns}language' => $this->languageFactory->getUserLanguage($user),
  459. ];
  460. $account = $this->accountManager->getAccount($user);
  461. $alternativeEmails = array_map(fn (IAccountProperty $property) => 'mailto:' . $property->getValue(), $account->getPropertyCollection(IAccountManager::COLLECTION_EMAIL)->getProperties());
  462. $email = $user->getSystemEMailAddress();
  463. if (!empty($email)) {
  464. $principal['{http://sabredav.org/ns}email-address'] = $email;
  465. }
  466. if (!empty($alternativeEmails)) {
  467. $principal['{DAV:}alternate-URI-set'] = $alternativeEmails;
  468. }
  469. return $principal;
  470. }
  471. public function getPrincipalPrefix() {
  472. return $this->principalPrefix;
  473. }
  474. /**
  475. * @param string $circleUniqueId
  476. * @return array|null
  477. */
  478. protected function circleToPrincipal($circleUniqueId) {
  479. if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
  480. return null;
  481. }
  482. try {
  483. $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($circleUniqueId, true);
  484. } catch (QueryException $ex) {
  485. return null;
  486. } catch (CircleNotFoundException $ex) {
  487. return null;
  488. }
  489. if (!$circle) {
  490. return null;
  491. }
  492. $principal = [
  493. 'uri' => 'principals/circles/' . $circleUniqueId,
  494. '{DAV:}displayname' => $circle->getDisplayName(),
  495. ];
  496. return $principal;
  497. }
  498. /**
  499. * Returns the list of circles a principal is a member of
  500. *
  501. * @param string $principal
  502. * @return array
  503. * @throws Exception
  504. * @throws \OCP\AppFramework\QueryException
  505. * @suppress PhanUndeclaredClassMethod
  506. */
  507. public function getCircleMembership($principal):array {
  508. if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
  509. return [];
  510. }
  511. [$prefix, $name] = \Sabre\Uri\split($principal);
  512. if ($this->hasCircles && $prefix === $this->principalPrefix) {
  513. $user = $this->userManager->get($name);
  514. if (!$user) {
  515. throw new Exception('Principal not found');
  516. }
  517. $circles = \OCA\Circles\Api\v1\Circles::joinedCircles($name, true);
  518. $circles = array_map(function ($circle) {
  519. /** @var \OCA\Circles\Model\Circle $circle */
  520. return 'principals/circles/' . urlencode($circle->getSingleId());
  521. }, $circles);
  522. return $circles;
  523. }
  524. return [];
  525. }
  526. /**
  527. * Get all email addresses associated to a principal.
  528. *
  529. * @param array $principal Data from getPrincipal*()
  530. * @return string[] All email addresses without the mailto: prefix
  531. */
  532. public function getEmailAddressesOfPrincipal(array $principal): array {
  533. $emailAddresses = [];
  534. if (isset($principal['{http://sabredav.org/ns}email-address'])) {
  535. $emailAddresses[] = $principal['{http://sabredav.org/ns}email-address'];
  536. }
  537. if (isset($principal['{DAV:}alternate-URI-set'])) {
  538. foreach ($principal['{DAV:}alternate-URI-set'] as $address) {
  539. if (str_starts_with($address, 'mailto:')) {
  540. $emailAddresses[] = substr($address, 7);
  541. }
  542. }
  543. }
  544. if (isset($principal['{urn:ietf:params:xml:ns:caldav}calendar-user-address-set'])) {
  545. foreach ($principal['{urn:ietf:params:xml:ns:caldav}calendar-user-address-set'] as $address) {
  546. if (str_starts_with($address, 'mailto:')) {
  547. $emailAddresses[] = substr($address, 7);
  548. }
  549. }
  550. }
  551. if (isset($principal['{http://calendarserver.org/ns/}email-address-set'])) {
  552. foreach ($principal['{http://calendarserver.org/ns/}email-address-set'] as $address) {
  553. if (str_starts_with($address, 'mailto:')) {
  554. $emailAddresses[] = substr($address, 7);
  555. }
  556. }
  557. }
  558. return array_values(array_unique($emailAddresses));
  559. }
  560. }