Backend.php 7.2 KB

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