Backend.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OCA\DAV\DAV\Sharing;
  9. use OCA\DAV\Connector\Sabre\Principal;
  10. use OCP\AppFramework\Db\TTransactional;
  11. use OCP\ICache;
  12. use OCP\ICacheFactory;
  13. use OCP\IGroupManager;
  14. use OCP\IUserManager;
  15. use Psr\Log\LoggerInterface;
  16. abstract class Backend {
  17. use TTransactional;
  18. public const ACCESS_OWNER = 1;
  19. public const ACCESS_READ_WRITE = 2;
  20. public const ACCESS_READ = 3;
  21. // 4 is already in use for public calendars
  22. public const ACCESS_UNSHARED = 5;
  23. private ICache $shareCache;
  24. public function __construct(private IUserManager $userManager,
  25. private IGroupManager $groupManager,
  26. private Principal $principalBackend,
  27. private ICacheFactory $cacheFactory,
  28. private SharingService $service,
  29. private LoggerInterface $logger,
  30. ) {
  31. $this->shareCache = $this->cacheFactory->createInMemory();
  32. }
  33. /**
  34. * @param list<array{href: string, commonName: string, readOnly: bool}> $add
  35. * @param list<string> $remove
  36. */
  37. public function updateShares(IShareable $shareable, array $add, array $remove, array $oldShares = []): void {
  38. $this->shareCache->clear();
  39. foreach ($add as $element) {
  40. $principal = $this->principalBackend->findByUri($element['href'], '');
  41. if (empty($principal)) {
  42. continue;
  43. }
  44. // We need to validate manually because some principals are only virtual
  45. // i.e. Group principals
  46. $principalparts = explode('/', $principal, 3);
  47. if (count($principalparts) !== 3 || $principalparts[0] !== 'principals' || !in_array($principalparts[1], ['users', 'groups', 'circles'], true)) {
  48. // Invalid principal
  49. continue;
  50. }
  51. // Don't add share for owner
  52. if($shareable->getOwner() !== null && strcasecmp($shareable->getOwner(), $principal) === 0) {
  53. continue;
  54. }
  55. $principalparts[2] = urldecode($principalparts[2]);
  56. if (($principalparts[1] === 'users' && !$this->userManager->userExists($principalparts[2])) ||
  57. ($principalparts[1] === 'groups' && !$this->groupManager->groupExists($principalparts[2]))) {
  58. // User or group does not exist
  59. continue;
  60. }
  61. $access = Backend::ACCESS_READ;
  62. if (isset($element['readOnly'])) {
  63. $access = $element['readOnly'] ? Backend::ACCESS_READ : Backend::ACCESS_READ_WRITE;
  64. }
  65. $this->service->shareWith($shareable->getResourceId(), $principal, $access);
  66. }
  67. foreach ($remove as $element) {
  68. $principal = $this->principalBackend->findByUri($element, '');
  69. if (empty($principal)) {
  70. continue;
  71. }
  72. // Don't add unshare for owner
  73. if($shareable->getOwner() !== null && strcasecmp($shareable->getOwner(), $principal) === 0) {
  74. continue;
  75. }
  76. // Delete any possible direct shares (since the frontend does not separate between them)
  77. $this->service->deleteShare($shareable->getResourceId(), $principal);
  78. // Check if a user has a groupshare that they're trying to free themselves from
  79. // If so we need to add a self::ACCESS_UNSHARED row
  80. if(!str_contains($principal, 'group')
  81. && $this->service->hasGroupShare($oldShares)
  82. ) {
  83. $this->service->unshare($shareable->getResourceId(), $principal);
  84. }
  85. }
  86. }
  87. public function deleteAllShares(int $resourceId): void {
  88. $this->shareCache->clear();
  89. $this->service->deleteAllShares($resourceId);
  90. }
  91. public function deleteAllSharesByUser(string $principaluri): void {
  92. $this->shareCache->clear();
  93. $this->service->deleteAllSharesByUser($principaluri);
  94. }
  95. /**
  96. * Returns the list of people whom this resource is shared with.
  97. *
  98. * Every element in this array should have the following properties:
  99. * * href - Often a mailto: address
  100. * * commonName - Optional, for example a first + last name
  101. * * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
  102. * * readOnly - boolean
  103. *
  104. * @param int $resourceId
  105. * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
  106. */
  107. public function getShares(int $resourceId): array {
  108. $cached = $this->shareCache->get((string)$resourceId);
  109. if ($cached) {
  110. return $cached;
  111. }
  112. $rows = $this->service->getShares($resourceId);
  113. $shares = [];
  114. foreach($rows as $row) {
  115. $p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
  116. $shares[] = [
  117. 'href' => "principal:{$row['principaluri']}",
  118. 'commonName' => isset($p['{DAV:}displayname']) ? (string)$p['{DAV:}displayname'] : '',
  119. 'status' => 1,
  120. 'readOnly' => (int) $row['access'] === Backend::ACCESS_READ,
  121. '{http://owncloud.org/ns}principal' => (string)$row['principaluri'],
  122. '{http://owncloud.org/ns}group-share' => isset($p['uri']) && str_starts_with($p['uri'], 'principals/groups')
  123. ];
  124. }
  125. $this->shareCache->set((string)$resourceId, $shares);
  126. return $shares;
  127. }
  128. public function preloadShares(array $resourceIds): void {
  129. $resourceIds = array_filter($resourceIds, function (int $resourceId) {
  130. return empty($this->shareCache->get((string)$resourceId));
  131. });
  132. if (empty($resourceIds)) {
  133. return;
  134. }
  135. $rows = $this->service->getSharesForIds($resourceIds);
  136. $sharesByResource = array_fill_keys($resourceIds, []);
  137. foreach($rows as $row) {
  138. $resourceId = (int)$row['resourceid'];
  139. $p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
  140. $sharesByResource[$resourceId][] = [
  141. 'href' => "principal:{$row['principaluri']}",
  142. 'commonName' => isset($p['{DAV:}displayname']) ? (string)$p['{DAV:}displayname'] : '',
  143. 'status' => 1,
  144. 'readOnly' => (int) $row['access'] === self::ACCESS_READ,
  145. '{http://owncloud.org/ns}principal' => (string)$row['principaluri'],
  146. '{http://owncloud.org/ns}group-share' => isset($p['uri']) && str_starts_with($p['uri'], 'principals/groups')
  147. ];
  148. $this->shareCache->set((string)$resourceId, $sharesByResource[$resourceId]);
  149. }
  150. }
  151. /**
  152. * For shared resources the sharee is set in the ACL of the resource
  153. *
  154. * @param int $resourceId
  155. * @param list<array{privilege: string, principal: string, protected: bool}> $acl
  156. * @param list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}> $shares
  157. * @return list<array{principal: string, privilege: string, protected: bool}>
  158. */
  159. public function applyShareAcl(array $shares, array $acl): array {
  160. foreach ($shares as $share) {
  161. $acl[] = [
  162. 'privilege' => '{DAV:}read',
  163. 'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
  164. 'protected' => true,
  165. ];
  166. if (!$share['readOnly']) {
  167. $acl[] = [
  168. 'privilege' => '{DAV:}write',
  169. 'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
  170. 'protected' => true,
  171. ];
  172. } elseif (in_array($this->service->getResourceType(), ['calendar','addressbook'])) {
  173. // Allow changing the properties of read only calendars,
  174. // so users can change the visibility.
  175. $acl[] = [
  176. 'privilege' => '{DAV:}write-properties',
  177. 'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
  178. 'protected' => true,
  179. ];
  180. }
  181. }
  182. return $acl;
  183. }
  184. }