Backend.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. * @author Thomas Citharel <nextcloud@tcit.fr>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OCA\DAV\DAV\Sharing;
  30. use OCA\DAV\Connector\Sabre\Principal;
  31. use OCP\AppFramework\Db\TTransactional;
  32. use OCP\Cache\CappedMemoryCache;
  33. use OCP\DB\QueryBuilder\IQueryBuilder;
  34. use OCP\IDBConnection;
  35. use OCP\IGroupManager;
  36. use OCP\IUserManager;
  37. class Backend {
  38. use TTransactional;
  39. private IDBConnection $db;
  40. private IUserManager $userManager;
  41. private IGroupManager $groupManager;
  42. private Principal $principalBackend;
  43. private string $resourceType;
  44. public const ACCESS_OWNER = 1;
  45. public const ACCESS_READ_WRITE = 2;
  46. public const ACCESS_READ = 3;
  47. private CappedMemoryCache $shareCache;
  48. public function __construct(IDBConnection $db, IUserManager $userManager, IGroupManager $groupManager, Principal $principalBackend, string $resourceType) {
  49. $this->db = $db;
  50. $this->userManager = $userManager;
  51. $this->groupManager = $groupManager;
  52. $this->principalBackend = $principalBackend;
  53. $this->resourceType = $resourceType;
  54. $this->shareCache = new CappedMemoryCache();
  55. }
  56. /**
  57. * @param list<array{href: string, commonName: string, readOnly: bool}> $add
  58. * @param list<string> $remove
  59. */
  60. public function updateShares(IShareable $shareable, array $add, array $remove): void {
  61. $this->shareCache->clear();
  62. $this->atomic(function () use ($shareable, $add, $remove) {
  63. foreach ($add as $element) {
  64. $principal = $this->principalBackend->findByUri($element['href'], '');
  65. if ($principal !== '') {
  66. $this->shareWith($shareable, $element);
  67. }
  68. }
  69. foreach ($remove as $element) {
  70. $principal = $this->principalBackend->findByUri($element, '');
  71. if ($principal !== '') {
  72. $this->unshare($shareable, $element);
  73. }
  74. }
  75. }, $this->db);
  76. }
  77. /**
  78. * @param array{href: string, commonName: string, readOnly: bool} $element
  79. */
  80. private function shareWith(IShareable $shareable, array $element): void {
  81. $this->shareCache->clear();
  82. $user = $element['href'];
  83. $parts = explode(':', $user, 2);
  84. if ($parts[0] !== 'principal') {
  85. return;
  86. }
  87. // don't share with owner
  88. if ($shareable->getOwner() === $parts[1]) {
  89. return;
  90. }
  91. $principal = explode('/', $parts[1], 3);
  92. if (count($principal) !== 3 || $principal[0] !== 'principals' || !in_array($principal[1], ['users', 'groups', 'circles'], true)) {
  93. // Invalid principal
  94. return;
  95. }
  96. $principal[2] = urldecode($principal[2]);
  97. if (($principal[1] === 'users' && !$this->userManager->userExists($principal[2])) ||
  98. ($principal[1] === 'groups' && !$this->groupManager->groupExists($principal[2]))) {
  99. // User or group does not exist
  100. return;
  101. }
  102. // remove the share if it already exists
  103. $this->unshare($shareable, $element['href']);
  104. $access = self::ACCESS_READ;
  105. if (isset($element['readOnly'])) {
  106. $access = $element['readOnly'] ? self::ACCESS_READ : self::ACCESS_READ_WRITE;
  107. }
  108. $query = $this->db->getQueryBuilder();
  109. $query->insert('dav_shares')
  110. ->values([
  111. 'principaluri' => $query->createNamedParameter($parts[1]),
  112. 'type' => $query->createNamedParameter($this->resourceType),
  113. 'access' => $query->createNamedParameter($access),
  114. 'resourceid' => $query->createNamedParameter($shareable->getResourceId())
  115. ]);
  116. $query->executeStatement();
  117. }
  118. public function deleteAllShares(int $resourceId): void {
  119. $this->shareCache->clear();
  120. $query = $this->db->getQueryBuilder();
  121. $query->delete('dav_shares')
  122. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
  123. ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
  124. ->executeStatement();
  125. }
  126. public function deleteAllSharesByUser(string $principaluri): void {
  127. $this->shareCache->clear();
  128. $query = $this->db->getQueryBuilder();
  129. $query->delete('dav_shares')
  130. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principaluri)))
  131. ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
  132. ->executeStatement();
  133. }
  134. private function unshare(IShareable $shareable, string $element): void {
  135. $this->shareCache->clear();
  136. $parts = explode(':', $element, 2);
  137. if ($parts[0] !== 'principal') {
  138. return;
  139. }
  140. // don't share with owner
  141. if ($shareable->getOwner() === $parts[1]) {
  142. return;
  143. }
  144. $query = $this->db->getQueryBuilder();
  145. $query->delete('dav_shares')
  146. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($shareable->getResourceId())))
  147. ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
  148. ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($parts[1])))
  149. ;
  150. $query->executeStatement();
  151. }
  152. /**
  153. * Returns the list of people whom this resource is shared with.
  154. *
  155. * Every element in this array should have the following properties:
  156. * * href - Often a mailto: address
  157. * * commonName - Optional, for example a first + last name
  158. * * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
  159. * * readOnly - boolean
  160. *
  161. * @param int $resourceId
  162. * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
  163. */
  164. public function getShares(int $resourceId): array {
  165. $cached = $this->shareCache->get($resourceId);
  166. if ($cached) {
  167. return $cached;
  168. }
  169. $query = $this->db->getQueryBuilder();
  170. $result = $query->select(['principaluri', 'access'])
  171. ->from('dav_shares')
  172. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId, IQueryBuilder::PARAM_INT)))
  173. ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
  174. ->groupBy(['principaluri', 'access'])
  175. ->executeQuery();
  176. $shares = [];
  177. while ($row = $result->fetch()) {
  178. $p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
  179. $shares[] = [
  180. 'href' => "principal:{$row['principaluri']}",
  181. 'commonName' => isset($p['{DAV:}displayname']) ? (string)$p['{DAV:}displayname'] : '',
  182. 'status' => 1,
  183. 'readOnly' => (int) $row['access'] === self::ACCESS_READ,
  184. '{http://owncloud.org/ns}principal' => (string)$row['principaluri'],
  185. '{http://owncloud.org/ns}group-share' => isset($p['uri']) ? str_starts_with($p['uri'], 'principals/groups') : false
  186. ];
  187. }
  188. $this->shareCache->set((string)$resourceId, $shares);
  189. return $shares;
  190. }
  191. public function preloadShares(array $resourceIds): void {
  192. $resourceIds = array_filter($resourceIds, function (int $resourceId) {
  193. return !isset($this->shareCache[$resourceId]);
  194. });
  195. if (count($resourceIds) === 0) {
  196. return;
  197. }
  198. $query = $this->db->getQueryBuilder();
  199. $result = $query->select(['resourceid', 'principaluri', 'access'])
  200. ->from('dav_shares')
  201. ->where($query->expr()->in('resourceid', $query->createNamedParameter($resourceIds, IQueryBuilder::PARAM_INT_ARRAY)))
  202. ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
  203. ->groupBy(['principaluri', 'access', 'resourceid'])
  204. ->executeQuery();
  205. $sharesByResource = array_fill_keys($resourceIds, []);
  206. while ($row = $result->fetch()) {
  207. $resourceId = (int)$row['resourceid'];
  208. $p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
  209. $sharesByResource[$resourceId][] = [
  210. 'href' => "principal:{$row['principaluri']}",
  211. 'commonName' => isset($p['{DAV:}displayname']) ? (string)$p['{DAV:}displayname'] : '',
  212. 'status' => 1,
  213. 'readOnly' => (int) $row['access'] === self::ACCESS_READ,
  214. '{http://owncloud.org/ns}principal' => (string)$row['principaluri'],
  215. '{http://owncloud.org/ns}group-share' => isset($p['uri']) ? str_starts_with($p['uri'], 'principals/groups') : false
  216. ];
  217. }
  218. foreach ($resourceIds as $resourceId) {
  219. $this->shareCache->set($resourceId, $sharesByResource[$resourceId]);
  220. }
  221. }
  222. /**
  223. * For shared resources the sharee is set in the ACL of the resource
  224. *
  225. * @param int $resourceId
  226. * @param list<array{privilege: string, principal: string, protected: bool}> $acl
  227. * @return list<array{privilege: string, principal: string, protected: bool}>
  228. */
  229. public function applyShareAcl(int $resourceId, array $acl): array {
  230. $shares = $this->getShares($resourceId);
  231. foreach ($shares as $share) {
  232. $acl[] = [
  233. 'privilege' => '{DAV:}read',
  234. 'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
  235. 'protected' => true,
  236. ];
  237. if (!$share['readOnly']) {
  238. $acl[] = [
  239. 'privilege' => '{DAV:}write',
  240. 'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
  241. 'protected' => true,
  242. ];
  243. } elseif (in_array($this->resourceType, ['calendar','addressbook'])) {
  244. // Allow changing the properties of read only calendars,
  245. // so users can change the visibility.
  246. $acl[] = [
  247. 'privilege' => '{DAV:}write-properties',
  248. 'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
  249. 'protected' => true,
  250. ];
  251. }
  252. }
  253. return $acl;
  254. }
  255. }