AbstractPrincipalBackend.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. <?php
  2. /**
  3. * @copyright 2019, Georg Ehrke <oc.list@georgehrke.com>
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Georg Ehrke <oc.list@georgehrke.com>
  7. * @author Roeland Jago Douma <roeland@famdouma.nl>
  8. * @author Anna Larch <anna.larch@gmx.net>
  9. *
  10. * @license GNU AGPL version 3 or any later version
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License as
  14. * published by the Free Software Foundation, either version 3 of the
  15. * License, or (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  24. *
  25. */
  26. namespace OCA\DAV\CalDAV\ResourceBooking;
  27. use OCA\DAV\CalDAV\Proxy\ProxyMapper;
  28. use OCA\DAV\Traits\PrincipalProxyTrait;
  29. use OCP\Calendar\Resource\IResourceMetadata;
  30. use OCP\Calendar\Room\IRoomMetadata;
  31. use OCP\DB\Exception;
  32. use OCP\DB\QueryBuilder\IQueryBuilder;
  33. use OCP\IDBConnection;
  34. use OCP\IGroupManager;
  35. use OCP\IUserSession;
  36. use Psr\Log\LoggerInterface;
  37. use Sabre\DAV\PropPatch;
  38. use Sabre\DAVACL\PrincipalBackend\BackendInterface;
  39. use function array_intersect;
  40. use function array_map;
  41. use function array_merge;
  42. use function array_unique;
  43. use function array_values;
  44. abstract class AbstractPrincipalBackend implements BackendInterface {
  45. /** @var IDBConnection */
  46. private $db;
  47. /** @var IUserSession */
  48. private $userSession;
  49. /** @var IGroupManager */
  50. private $groupManager;
  51. private LoggerInterface $logger;
  52. /** @var ProxyMapper */
  53. private $proxyMapper;
  54. /** @var string */
  55. private $principalPrefix;
  56. /** @var string */
  57. private $dbTableName;
  58. /** @var string */
  59. private $dbMetaDataTableName;
  60. /** @var string */
  61. private $dbForeignKeyName;
  62. /** @var string */
  63. private $cuType;
  64. public function __construct(IDBConnection $dbConnection,
  65. IUserSession $userSession,
  66. IGroupManager $groupManager,
  67. LoggerInterface $logger,
  68. ProxyMapper $proxyMapper,
  69. string $principalPrefix,
  70. string $dbPrefix,
  71. string $cuType) {
  72. $this->db = $dbConnection;
  73. $this->userSession = $userSession;
  74. $this->groupManager = $groupManager;
  75. $this->logger = $logger;
  76. $this->proxyMapper = $proxyMapper;
  77. $this->principalPrefix = $principalPrefix;
  78. $this->dbTableName = 'calendar_' . $dbPrefix . 's';
  79. $this->dbMetaDataTableName = $this->dbTableName . '_md';
  80. $this->dbForeignKeyName = $dbPrefix . '_id';
  81. $this->cuType = $cuType;
  82. }
  83. use PrincipalProxyTrait;
  84. /**
  85. * Returns a list of principals based on a prefix.
  86. *
  87. * This prefix will often contain something like 'principals'. You are only
  88. * expected to return principals that are in this base path.
  89. *
  90. * You are expected to return at least a 'uri' for every user, you can
  91. * return any additional properties if you wish so. Common properties are:
  92. * {DAV:}displayname
  93. *
  94. * @param string $prefixPath
  95. * @return string[]
  96. */
  97. public function getPrincipalsByPrefix($prefixPath): array {
  98. $principals = [];
  99. if ($prefixPath === $this->principalPrefix) {
  100. $query = $this->db->getQueryBuilder();
  101. $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
  102. ->from($this->dbTableName);
  103. $stmt = $query->execute();
  104. $metaDataQuery = $this->db->getQueryBuilder();
  105. $metaDataQuery->select([$this->dbForeignKeyName, 'key', 'value'])
  106. ->from($this->dbMetaDataTableName);
  107. $metaDataStmt = $metaDataQuery->execute();
  108. $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
  109. $metaDataById = [];
  110. foreach ($metaDataRows as $metaDataRow) {
  111. if (!isset($metaDataById[$metaDataRow[$this->dbForeignKeyName]])) {
  112. $metaDataById[$metaDataRow[$this->dbForeignKeyName]] = [];
  113. }
  114. $metaDataById[$metaDataRow[$this->dbForeignKeyName]][$metaDataRow['key']] =
  115. $metaDataRow['value'];
  116. }
  117. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  118. $id = $row['id'];
  119. if (isset($metaDataById[$id])) {
  120. $principals[] = $this->rowToPrincipal($row, $metaDataById[$id]);
  121. } else {
  122. $principals[] = $this->rowToPrincipal($row);
  123. }
  124. }
  125. $stmt->closeCursor();
  126. }
  127. return $principals;
  128. }
  129. /**
  130. * Returns a specific principal, specified by its path.
  131. * The returned structure should be the exact same as from
  132. * getPrincipalsByPrefix.
  133. *
  134. * @param string $prefixPath
  135. *
  136. * @return array
  137. */
  138. public function getPrincipalByPath($path) {
  139. if (!str_starts_with($path, $this->principalPrefix)) {
  140. return null;
  141. }
  142. [, $name] = \Sabre\Uri\split($path);
  143. [$backendId, $resourceId] = explode('-', $name, 2);
  144. $query = $this->db->getQueryBuilder();
  145. $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
  146. ->from($this->dbTableName)
  147. ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
  148. ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
  149. $stmt = $query->execute();
  150. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  151. if (!$row) {
  152. return null;
  153. }
  154. $metaDataQuery = $this->db->getQueryBuilder();
  155. $metaDataQuery->select(['key', 'value'])
  156. ->from($this->dbMetaDataTableName)
  157. ->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id'])));
  158. $metaDataStmt = $metaDataQuery->execute();
  159. $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
  160. $metadata = [];
  161. foreach ($metaDataRows as $metaDataRow) {
  162. $metadata[$metaDataRow['key']] = $metaDataRow['value'];
  163. }
  164. return $this->rowToPrincipal($row, $metadata);
  165. }
  166. /**
  167. * @param int $id
  168. * @return string[]|null
  169. */
  170. public function getPrincipalById($id): ?array {
  171. $query = $this->db->getQueryBuilder();
  172. $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname'])
  173. ->from($this->dbTableName)
  174. ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
  175. $stmt = $query->execute();
  176. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  177. if (!$row) {
  178. return null;
  179. }
  180. $metaDataQuery = $this->db->getQueryBuilder();
  181. $metaDataQuery->select(['key', 'value'])
  182. ->from($this->dbMetaDataTableName)
  183. ->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id'])));
  184. $metaDataStmt = $metaDataQuery->execute();
  185. $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC);
  186. $metadata = [];
  187. foreach ($metaDataRows as $metaDataRow) {
  188. $metadata[$metaDataRow['key']] = $metaDataRow['value'];
  189. }
  190. return $this->rowToPrincipal($row, $metadata);
  191. }
  192. /**
  193. * @param string $path
  194. * @param PropPatch $propPatch
  195. * @return int
  196. */
  197. public function updatePrincipal($path, PropPatch $propPatch): int {
  198. return 0;
  199. }
  200. /**
  201. * @param string $prefixPath
  202. * @param string $test
  203. *
  204. * @return array
  205. */
  206. public function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') {
  207. $results = [];
  208. if (\count($searchProperties) === 0) {
  209. return [];
  210. }
  211. if ($prefixPath !== $this->principalPrefix) {
  212. return [];
  213. }
  214. $user = $this->userSession->getUser();
  215. if (!$user) {
  216. return [];
  217. }
  218. $usersGroups = $this->groupManager->getUserGroupIds($user);
  219. foreach ($searchProperties as $prop => $value) {
  220. switch ($prop) {
  221. case '{http://sabredav.org/ns}email-address':
  222. $query = $this->db->getQueryBuilder();
  223. $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
  224. ->from($this->dbTableName)
  225. ->where($query->expr()->iLike('email', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
  226. $stmt = $query->execute();
  227. $principals = [];
  228. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  229. if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
  230. continue;
  231. }
  232. $principals[] = $this->rowToPrincipal($row)['uri'];
  233. }
  234. $results[] = $principals;
  235. $stmt->closeCursor();
  236. break;
  237. case '{DAV:}displayname':
  238. $query = $this->db->getQueryBuilder();
  239. $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
  240. ->from($this->dbTableName)
  241. ->where($query->expr()->iLike('displayname', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
  242. $stmt = $query->execute();
  243. $principals = [];
  244. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  245. if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
  246. continue;
  247. }
  248. $principals[] = $this->rowToPrincipal($row)['uri'];
  249. }
  250. $results[] = $principals;
  251. $stmt->closeCursor();
  252. break;
  253. case '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set':
  254. // If you add support for more search properties that qualify as a user-address,
  255. // please also add them to the array below
  256. $results[] = $this->searchPrincipals($this->principalPrefix, [
  257. '{http://sabredav.org/ns}email-address' => $value,
  258. ], 'anyof');
  259. break;
  260. case IRoomMetadata::FEATURES:
  261. $results[] = $this->searchPrincipalsByRoomFeature($prop, $value);
  262. break;
  263. case IRoomMetadata::CAPACITY:
  264. case IResourceMetadata::VEHICLE_SEATING_CAPACITY:
  265. $results[] = $this->searchPrincipalsByCapacity($prop, $value);
  266. break;
  267. default:
  268. $results[] = $this->searchPrincipalsByMetadataKey($prop, $value, $usersGroups);
  269. break;
  270. }
  271. }
  272. // results is an array of arrays, so this is not the first search result
  273. // but the results of the first searchProperty
  274. if (count($results) === 1) {
  275. return $results[0];
  276. }
  277. switch ($test) {
  278. case 'anyof':
  279. return array_values(array_unique(array_merge(...$results)));
  280. case 'allof':
  281. default:
  282. return array_values(array_intersect(...$results));
  283. }
  284. }
  285. /**
  286. * @param string $key
  287. * @return IQueryBuilder
  288. */
  289. private function getMetadataQuery(string $key): IQueryBuilder {
  290. $query = $this->db->getQueryBuilder();
  291. $query->select([$this->dbForeignKeyName])
  292. ->from($this->dbMetaDataTableName)
  293. ->where($query->expr()->eq('key', $query->createNamedParameter($key)));
  294. return $query;
  295. }
  296. /**
  297. * Searches principals based on their metadata keys.
  298. * This allows to search for all principals with a specific key.
  299. * e.g.:
  300. * '{http://nextcloud.com/ns}room-building-address' => 'ABC Street 123, ...'
  301. *
  302. * @param string $key
  303. * @param string $value
  304. * @param string[] $usersGroups
  305. * @return string[]
  306. */
  307. private function searchPrincipalsByMetadataKey(string $key, string $value, array $usersGroups = []): array {
  308. $query = $this->getMetadataQuery($key);
  309. $query->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%')));
  310. return $this->getRows($query, $usersGroups);
  311. }
  312. /**
  313. * Searches principals based on room features
  314. * e.g.:
  315. * '{http://nextcloud.com/ns}room-features' => 'TV,PROJECTOR'
  316. *
  317. * @param string $key
  318. * @param string $value
  319. * @param string[] $usersGroups
  320. * @return string[]
  321. */
  322. private function searchPrincipalsByRoomFeature(string $key, string $value, array $usersGroups = []): array {
  323. $query = $this->getMetadataQuery($key);
  324. foreach (explode(',', $value) as $v) {
  325. $query->andWhere($query->expr()->iLike('value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($v) . '%')));
  326. }
  327. return $this->getRows($query, $usersGroups);
  328. }
  329. /**
  330. * Searches principals based on room seating capacity or vehicle capacity
  331. * e.g.:
  332. * '{http://nextcloud.com/ns}room-seating-capacity' => '100'
  333. *
  334. * @param string $key
  335. * @param string $value
  336. * @param string[] $usersGroups
  337. * @return string[]
  338. */
  339. private function searchPrincipalsByCapacity(string $key, string $value, array $usersGroups = []): array {
  340. $query = $this->getMetadataQuery($key);
  341. $query->andWhere($query->expr()->gte('value', $query->createNamedParameter($value)));
  342. return $this->getRows($query, $usersGroups);
  343. }
  344. /**
  345. * @param IQueryBuilder $query
  346. * @param string[] $usersGroups
  347. * @return string[]
  348. */
  349. private function getRows(IQueryBuilder $query, array $usersGroups): array {
  350. try {
  351. $stmt = $query->executeQuery();
  352. } catch (Exception $e) {
  353. $this->logger->error("Could not search resources: " . $e->getMessage(), ['exception' => $e]);
  354. }
  355. $rows = [];
  356. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  357. $principalRow = $this->getPrincipalById($row[$this->dbForeignKeyName]);
  358. if (!$principalRow) {
  359. continue;
  360. }
  361. $rows[] = $principalRow;
  362. }
  363. $stmt->closeCursor();
  364. $filteredRows = array_filter($rows, function ($row) use ($usersGroups) {
  365. return $this->isAllowedToAccessResource($row, $usersGroups);
  366. });
  367. return array_map(static function ($row): string {
  368. return $row['uri'];
  369. }, $filteredRows);
  370. }
  371. /**
  372. * @param string $uri
  373. * @param string $principalPrefix
  374. * @return null|string
  375. * @throws Exception
  376. */
  377. public function findByUri($uri, $principalPrefix): ?string {
  378. $user = $this->userSession->getUser();
  379. if (!$user) {
  380. return null;
  381. }
  382. $usersGroups = $this->groupManager->getUserGroupIds($user);
  383. if (str_starts_with($uri, 'mailto:')) {
  384. $email = substr($uri, 7);
  385. $query = $this->db->getQueryBuilder();
  386. $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
  387. ->from($this->dbTableName)
  388. ->where($query->expr()->eq('email', $query->createNamedParameter($email)));
  389. $stmt = $query->execute();
  390. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  391. if (!$row) {
  392. return null;
  393. }
  394. if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
  395. return null;
  396. }
  397. return $this->rowToPrincipal($row)['uri'];
  398. }
  399. if (str_starts_with($uri, 'principal:')) {
  400. $path = substr($uri, 10);
  401. if (!str_starts_with($path, $this->principalPrefix)) {
  402. return null;
  403. }
  404. [, $name] = \Sabre\Uri\split($path);
  405. [$backendId, $resourceId] = explode('-', $name, 2);
  406. $query = $this->db->getQueryBuilder();
  407. $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions'])
  408. ->from($this->dbTableName)
  409. ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId)))
  410. ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId)));
  411. $stmt = $query->execute();
  412. $row = $stmt->fetch(\PDO::FETCH_ASSOC);
  413. if (!$row) {
  414. return null;
  415. }
  416. if (!$this->isAllowedToAccessResource($row, $usersGroups)) {
  417. return null;
  418. }
  419. return $this->rowToPrincipal($row)['uri'];
  420. }
  421. return null;
  422. }
  423. /**
  424. * convert database row to principal
  425. *
  426. * @param string[] $row
  427. * @param string[] $metadata
  428. * @return string[]
  429. */
  430. private function rowToPrincipal(array $row, array $metadata = []): array {
  431. return array_merge([
  432. 'uri' => $this->principalPrefix . '/' . $row['backend_id'] . '-' . $row['resource_id'],
  433. '{DAV:}displayname' => $row['displayname'],
  434. '{http://sabredav.org/ns}email-address' => $row['email'],
  435. '{urn:ietf:params:xml:ns:caldav}calendar-user-type' => $this->cuType,
  436. ], $metadata);
  437. }
  438. /**
  439. * @param array $row
  440. * @param array $userGroups
  441. * @return bool
  442. */
  443. private function isAllowedToAccessResource(array $row, array $userGroups): bool {
  444. if (!isset($row['group_restrictions']) ||
  445. $row['group_restrictions'] === null ||
  446. $row['group_restrictions'] === '') {
  447. return true;
  448. }
  449. // group restrictions contains something, but not parsable, deny access and log warning
  450. $json = json_decode($row['group_restrictions'], null, 512, JSON_THROW_ON_ERROR);
  451. if (!\is_array($json)) {
  452. $this->logger->info('group_restrictions field could not be parsed for ' . $this->dbTableName . '::' . $row['id'] . ', denying access to resource');
  453. return false;
  454. }
  455. // empty array => no group restrictions
  456. if (empty($json)) {
  457. return true;
  458. }
  459. return !empty(array_intersect($json, $userGroups));
  460. }
  461. }