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

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