Principal.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  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. } elseif ($prefix === 'principals/system') {
  187. return [
  188. 'uri' => 'principals/system/' . $name,
  189. '{DAV:}displayname' => $this->languageFactory->get('dav')->t("Accounts"),
  190. ];
  191. }
  192. return null;
  193. }
  194. /**
  195. * Returns the list of groups a principal is a member of
  196. *
  197. * @param string $principal
  198. * @param bool $needGroups
  199. * @return array
  200. * @throws Exception
  201. */
  202. public function getGroupMembership($principal, $needGroups = false) {
  203. [$prefix, $name] = \Sabre\Uri\split($principal);
  204. if ($prefix !== $this->principalPrefix) {
  205. return [];
  206. }
  207. $user = $this->userManager->get($name);
  208. if (!$user) {
  209. throw new Exception('Principal not found');
  210. }
  211. $groups = [];
  212. if ($this->hasGroups || $needGroups) {
  213. $userGroups = $this->groupManager->getUserGroups($user);
  214. foreach ($userGroups as $userGroup) {
  215. $groups[] = 'principals/groups/' . urlencode($userGroup->getGID());
  216. }
  217. }
  218. $groups = array_unique(array_merge(
  219. $groups,
  220. $this->traitGetGroupMembership($principal, $needGroups)
  221. ));
  222. return $groups;
  223. }
  224. /**
  225. * @param string $path
  226. * @param PropPatch $propPatch
  227. * @return int
  228. */
  229. public function updatePrincipal($path, PropPatch $propPatch) {
  230. // Updating schedule-default-calendar-URL is handled in CustomPropertiesBackend
  231. return 0;
  232. }
  233. /**
  234. * Search user principals
  235. *
  236. * @param array $searchProperties
  237. * @param string $test
  238. * @return array
  239. */
  240. protected function searchUserPrincipals(array $searchProperties, $test = 'allof') {
  241. $results = [];
  242. // If sharing is disabled, return the empty array
  243. $shareAPIEnabled = $this->shareManager->shareApiEnabled();
  244. if (!$shareAPIEnabled) {
  245. return [];
  246. }
  247. $allowEnumeration = $this->shareManager->allowEnumeration();
  248. $limitEnumerationGroup = $this->shareManager->limitEnumerationToGroups();
  249. $limitEnumerationPhone = $this->shareManager->limitEnumerationToPhone();
  250. $allowEnumerationFullMatch = $this->shareManager->allowEnumerationFullMatch();
  251. $ignoreSecondDisplayName = $this->shareManager->ignoreSecondDisplayName();
  252. $matchEmail = $this->shareManager->matchEmail();
  253. // If sharing is restricted to group members only,
  254. // return only members that have groups in common
  255. $restrictGroups = false;
  256. $currentUser = $this->userSession->getUser();
  257. if ($this->shareManager->shareWithGroupMembersOnly()) {
  258. if (!$currentUser instanceof IUser) {
  259. return [];
  260. }
  261. $restrictGroups = $this->groupManager->getUserGroupIds($currentUser);
  262. }
  263. $currentUserGroups = [];
  264. if ($limitEnumerationGroup) {
  265. if ($currentUser instanceof IUser) {
  266. $currentUserGroups = $this->groupManager->getUserGroupIds($currentUser);
  267. }
  268. }
  269. $searchLimit = $this->config->getSystemValueInt('sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT);
  270. if ($searchLimit <= 0) {
  271. $searchLimit = null;
  272. }
  273. foreach ($searchProperties as $prop => $value) {
  274. switch ($prop) {
  275. case '{http://sabredav.org/ns}email-address':
  276. if (!$allowEnumeration) {
  277. if ($allowEnumerationFullMatch && $matchEmail) {
  278. $users = $this->userManager->getByEmail($value);
  279. } else {
  280. $users = [];
  281. }
  282. } else {
  283. $users = $this->userManager->getByEmail($value);
  284. $users = \array_filter($users, function (IUser $user) use ($currentUser, $value, $limitEnumerationPhone, $limitEnumerationGroup, $allowEnumerationFullMatch, $currentUserGroups) {
  285. if ($allowEnumerationFullMatch && $user->getSystemEMailAddress() === $value) {
  286. return true;
  287. }
  288. if ($limitEnumerationPhone
  289. && $currentUser instanceof IUser
  290. && $this->knownUserService->isKnownToUser($currentUser->getUID(), $user->getUID())) {
  291. // Synced phonebook match
  292. return true;
  293. }
  294. if (!$limitEnumerationGroup) {
  295. // No limitation on enumeration, all allowed
  296. return true;
  297. }
  298. return !empty($currentUserGroups) && !empty(array_intersect(
  299. $this->groupManager->getUserGroupIds($user),
  300. $currentUserGroups
  301. ));
  302. });
  303. }
  304. $results[] = array_reduce($users, function (array $carry, IUser $user) use ($restrictGroups) {
  305. // is sharing restricted to groups only?
  306. if ($restrictGroups !== false) {
  307. $userGroups = $this->groupManager->getUserGroupIds($user);
  308. if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
  309. return $carry;
  310. }
  311. }
  312. $carry[] = $this->principalPrefix . '/' . $user->getUID();
  313. return $carry;
  314. }, []);
  315. break;
  316. case '{DAV:}displayname':
  317. if (!$allowEnumeration) {
  318. if ($allowEnumerationFullMatch) {
  319. $lowerSearch = strtolower($value);
  320. $users = $this->userManager->searchDisplayName($value, $searchLimit);
  321. $users = \array_filter($users, static function (IUser $user) use ($lowerSearch, $ignoreSecondDisplayName) {
  322. $lowerDisplayName = strtolower($user->getDisplayName());
  323. return $lowerDisplayName === $lowerSearch || ($ignoreSecondDisplayName && trim(preg_replace('/ \(.*\)$/', '', $lowerDisplayName)) === $lowerSearch);
  324. });
  325. } else {
  326. $users = [];
  327. }
  328. } else {
  329. $users = $this->userManager->searchDisplayName($value, $searchLimit);
  330. $users = \array_filter($users, function (IUser $user) use ($currentUser, $value, $limitEnumerationPhone, $limitEnumerationGroup, $allowEnumerationFullMatch, $currentUserGroups) {
  331. if ($allowEnumerationFullMatch && $user->getDisplayName() === $value) {
  332. return true;
  333. }
  334. if ($limitEnumerationPhone
  335. && $currentUser instanceof IUser
  336. && $this->knownUserService->isKnownToUser($currentUser->getUID(), $user->getUID())) {
  337. // Synced phonebook match
  338. return true;
  339. }
  340. if (!$limitEnumerationGroup) {
  341. // No limitation on enumeration, all allowed
  342. return true;
  343. }
  344. return !empty($currentUserGroups) && !empty(array_intersect(
  345. $this->groupManager->getUserGroupIds($user),
  346. $currentUserGroups
  347. ));
  348. });
  349. }
  350. $results[] = array_reduce($users, function (array $carry, IUser $user) use ($restrictGroups) {
  351. // is sharing restricted to groups only?
  352. if ($restrictGroups !== false) {
  353. $userGroups = $this->groupManager->getUserGroupIds($user);
  354. if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
  355. return $carry;
  356. }
  357. }
  358. $carry[] = $this->principalPrefix . '/' . $user->getUID();
  359. return $carry;
  360. }, []);
  361. break;
  362. case '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set':
  363. // If you add support for more search properties that qualify as a user-address,
  364. // please also add them to the array below
  365. $results[] = $this->searchUserPrincipals([
  366. // In theory this should also search for principal:principals/users/...
  367. // but that's used internally only anyway and i don't know of any client querying that
  368. '{http://sabredav.org/ns}email-address' => $value,
  369. ], 'anyof');
  370. break;
  371. default:
  372. $results[] = [];
  373. break;
  374. }
  375. }
  376. // results is an array of arrays, so this is not the first search result
  377. // but the results of the first searchProperty
  378. if (count($results) === 1) {
  379. return $results[0];
  380. }
  381. switch ($test) {
  382. case 'anyof':
  383. return array_values(array_unique(array_merge(...$results)));
  384. case 'allof':
  385. default:
  386. return array_values(array_intersect(...$results));
  387. }
  388. }
  389. /**
  390. * @param string $prefixPath
  391. * @param array $searchProperties
  392. * @param string $test
  393. * @return array
  394. */
  395. public function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
  396. if (count($searchProperties) === 0) {
  397. return [];
  398. }
  399. switch ($prefixPath) {
  400. case 'principals/users':
  401. return $this->searchUserPrincipals($searchProperties, $test);
  402. default:
  403. return [];
  404. }
  405. }
  406. /**
  407. * @param string $uri
  408. * @param string $principalPrefix
  409. * @return string
  410. */
  411. public function findByUri($uri, $principalPrefix) {
  412. // If sharing is disabled, return the empty array
  413. $shareAPIEnabled = $this->shareManager->shareApiEnabled();
  414. if (!$shareAPIEnabled) {
  415. return null;
  416. }
  417. // If sharing is restricted to group members only,
  418. // return only members that have groups in common
  419. $restrictGroups = false;
  420. if ($this->shareManager->shareWithGroupMembersOnly()) {
  421. $user = $this->userSession->getUser();
  422. if (!$user) {
  423. return null;
  424. }
  425. $restrictGroups = $this->groupManager->getUserGroupIds($user);
  426. }
  427. if (str_starts_with($uri, 'mailto:')) {
  428. if ($principalPrefix === 'principals/users') {
  429. $users = $this->userManager->getByEmail(substr($uri, 7));
  430. if (count($users) !== 1) {
  431. return null;
  432. }
  433. $user = $users[0];
  434. if ($restrictGroups !== false) {
  435. $userGroups = $this->groupManager->getUserGroupIds($user);
  436. if (count(array_intersect($userGroups, $restrictGroups)) === 0) {
  437. return null;
  438. }
  439. }
  440. return $this->principalPrefix . '/' . $user->getUID();
  441. }
  442. }
  443. if (str_starts_with($uri, 'principal:')) {
  444. $principal = substr($uri, 10);
  445. $principal = $this->getPrincipalByPath($principal);
  446. if ($principal !== null) {
  447. return $principal['uri'];
  448. }
  449. }
  450. return null;
  451. }
  452. /**
  453. * @param IUser $user
  454. * @return array
  455. * @throws PropertyDoesNotExistException
  456. */
  457. protected function userToPrincipal($user) {
  458. $userId = $user->getUID();
  459. $displayName = $user->getDisplayName();
  460. $principal = [
  461. 'uri' => $this->principalPrefix . '/' . $userId,
  462. '{DAV:}displayname' => is_null($displayName) ? $userId : $displayName,
  463. '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => 'INDIVIDUAL',
  464. '{http://nextcloud.com/ns}language' => $this->languageFactory->getUserLanguage($user),
  465. ];
  466. $account = $this->accountManager->getAccount($user);
  467. $alternativeEmails = array_map(fn (IAccountProperty $property) => 'mailto:' . $property->getValue(), $account->getPropertyCollection(IAccountManager::COLLECTION_EMAIL)->getProperties());
  468. $email = $user->getSystemEMailAddress();
  469. if (!empty($email)) {
  470. $principal['{http://sabredav.org/ns}email-address'] = $email;
  471. }
  472. if (!empty($alternativeEmails)) {
  473. $principal['{DAV:}alternate-URI-set'] = $alternativeEmails;
  474. }
  475. return $principal;
  476. }
  477. public function getPrincipalPrefix() {
  478. return $this->principalPrefix;
  479. }
  480. /**
  481. * @param string $circleUniqueId
  482. * @return array|null
  483. */
  484. protected function circleToPrincipal($circleUniqueId) {
  485. if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
  486. return null;
  487. }
  488. try {
  489. $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($circleUniqueId, true);
  490. } catch (QueryException $ex) {
  491. return null;
  492. } catch (CircleNotFoundException $ex) {
  493. return null;
  494. }
  495. if (!$circle) {
  496. return null;
  497. }
  498. $principal = [
  499. 'uri' => 'principals/circles/' . $circleUniqueId,
  500. '{DAV:}displayname' => $circle->getDisplayName(),
  501. ];
  502. return $principal;
  503. }
  504. /**
  505. * Returns the list of circles a principal is a member of
  506. *
  507. * @param string $principal
  508. * @return array
  509. * @throws Exception
  510. * @throws \OCP\AppFramework\QueryException
  511. * @suppress PhanUndeclaredClassMethod
  512. */
  513. public function getCircleMembership($principal):array {
  514. if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) {
  515. return [];
  516. }
  517. [$prefix, $name] = \Sabre\Uri\split($principal);
  518. if ($this->hasCircles && $prefix === $this->principalPrefix) {
  519. $user = $this->userManager->get($name);
  520. if (!$user) {
  521. throw new Exception('Principal not found');
  522. }
  523. $circles = \OCA\Circles\Api\v1\Circles::joinedCircles($name, true);
  524. $circles = array_map(function ($circle) {
  525. /** @var \OCA\Circles\Model\Circle $circle */
  526. return 'principals/circles/' . urlencode($circle->getSingleId());
  527. }, $circles);
  528. return $circles;
  529. }
  530. return [];
  531. }
  532. /**
  533. * Get all email addresses associated to a principal.
  534. *
  535. * @param array $principal Data from getPrincipal*()
  536. * @return string[] All email addresses without the mailto: prefix
  537. */
  538. public function getEmailAddressesOfPrincipal(array $principal): array {
  539. $emailAddresses = [];
  540. if (isset($principal['{http://sabredav.org/ns}email-address'])) {
  541. $emailAddresses[] = $principal['{http://sabredav.org/ns}email-address'];
  542. }
  543. if (isset($principal['{DAV:}alternate-URI-set'])) {
  544. foreach ($principal['{DAV:}alternate-URI-set'] as $address) {
  545. if (str_starts_with($address, 'mailto:')) {
  546. $emailAddresses[] = substr($address, 7);
  547. }
  548. }
  549. }
  550. if (isset($principal['{urn:ietf:params:xml:ns:caldav}calendar-user-address-set'])) {
  551. foreach ($principal['{urn:ietf:params:xml:ns:caldav}calendar-user-address-set'] as $address) {
  552. if (str_starts_with($address, 'mailto:')) {
  553. $emailAddresses[] = substr($address, 7);
  554. }
  555. }
  556. }
  557. if (isset($principal['{http://calendarserver.org/ns/}email-address-set'])) {
  558. foreach ($principal['{http://calendarserver.org/ns/}email-address-set'] as $address) {
  559. if (str_starts_with($address, 'mailto:')) {
  560. $emailAddresses[] = substr($address, 7);
  561. }
  562. }
  563. }
  564. return array_values(array_unique($emailAddresses));
  565. }
  566. }