Backend.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Lukas Reschke <lukas@statuscode.ch>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Thomas Citharel <nextcloud@tcit.fr>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Anna Larch <anna.larch@gmx.net>
  15. *
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OCA\DAV\DAV\Sharing;
  32. use OCA\DAV\Connector\Sabre\Principal;
  33. use OCP\AppFramework\Db\TTransactional;
  34. use OCP\ICache;
  35. use OCP\ICacheFactory;
  36. use OCP\IGroupManager;
  37. use OCP\IUserManager;
  38. use Psr\Log\LoggerInterface;
  39. abstract class Backend {
  40. use TTransactional;
  41. public const ACCESS_OWNER = 1;
  42. public const ACCESS_READ_WRITE = 2;
  43. public const ACCESS_READ = 3;
  44. // 4 is already in use for public calendars
  45. public const ACCESS_UNSHARED = 5;
  46. private ICache $shareCache;
  47. public function __construct(private IUserManager $userManager,
  48. private IGroupManager $groupManager,
  49. private Principal $principalBackend,
  50. private ICacheFactory $cacheFactory,
  51. private SharingService $service,
  52. private LoggerInterface $logger,
  53. ) {
  54. $this->shareCache = $this->cacheFactory->createInMemory();
  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, array $oldShares = []): void {
  61. $this->shareCache->clear();
  62. foreach ($add as $element) {
  63. $principal = $this->principalBackend->findByUri($element['href'], '');
  64. if (empty($principal)) {
  65. continue;
  66. }
  67. // We need to validate manually because some principals are only virtual
  68. // i.e. Group principals
  69. $principalparts = explode('/', $principal, 3);
  70. if (count($principalparts) !== 3 || $principalparts[0] !== 'principals' || !in_array($principalparts[1], ['users', 'groups', 'circles'], true)) {
  71. // Invalid principal
  72. continue;
  73. }
  74. // Don't add share for owner
  75. if($shareable->getOwner() !== null && strcasecmp($shareable->getOwner(), $principal) === 0) {
  76. continue;
  77. }
  78. $principalparts[2] = urldecode($principalparts[2]);
  79. if (($principalparts[1] === 'users' && !$this->userManager->userExists($principalparts[2])) ||
  80. ($principalparts[1] === 'groups' && !$this->groupManager->groupExists($principalparts[2]))) {
  81. // User or group does not exist
  82. continue;
  83. }
  84. $access = Backend::ACCESS_READ;
  85. if (isset($element['readOnly'])) {
  86. $access = $element['readOnly'] ? Backend::ACCESS_READ : Backend::ACCESS_READ_WRITE;
  87. }
  88. $this->service->shareWith($shareable->getResourceId(), $principal, $access);
  89. }
  90. foreach ($remove as $element) {
  91. $principal = $this->principalBackend->findByUri($element, '');
  92. if (empty($principal)) {
  93. continue;
  94. }
  95. // Don't add unshare for owner
  96. if($shareable->getOwner() !== null && strcasecmp($shareable->getOwner(), $principal) === 0) {
  97. continue;
  98. }
  99. // Delete any possible direct shares (since the frontend does not separate between them)
  100. $this->service->deleteShare($shareable->getResourceId(), $principal);
  101. // Check if a user has a groupshare that they're trying to free themselves from
  102. // If so we need to add a self::ACCESS_UNSHARED row
  103. if(!str_contains($principal, 'group')
  104. && $this->service->hasGroupShare($oldShares)
  105. ) {
  106. $this->service->unshare($shareable->getResourceId(), $principal);
  107. }
  108. }
  109. }
  110. public function deleteAllShares(int $resourceId): void {
  111. $this->shareCache->clear();
  112. $this->service->deleteAllShares($resourceId);
  113. }
  114. public function deleteAllSharesByUser(string $principaluri): void {
  115. $this->shareCache->clear();
  116. $this->service->deleteAllSharesByUser($principaluri);
  117. }
  118. /**
  119. * Returns the list of people whom this resource is shared with.
  120. *
  121. * Every element in this array should have the following properties:
  122. * * href - Often a mailto: address
  123. * * commonName - Optional, for example a first + last name
  124. * * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
  125. * * readOnly - boolean
  126. *
  127. * @param int $resourceId
  128. * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
  129. */
  130. public function getShares(int $resourceId): array {
  131. $cached = $this->shareCache->get((string)$resourceId);
  132. if ($cached) {
  133. return $cached;
  134. }
  135. $rows = $this->service->getShares($resourceId);
  136. $shares = [];
  137. foreach($rows as $row) {
  138. $p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
  139. $shares[] = [
  140. 'href' => "principal:{$row['principaluri']}",
  141. 'commonName' => isset($p['{DAV:}displayname']) ? (string)$p['{DAV:}displayname'] : '',
  142. 'status' => 1,
  143. 'readOnly' => (int) $row['access'] === Backend::ACCESS_READ,
  144. '{http://owncloud.org/ns}principal' => (string)$row['principaluri'],
  145. '{http://owncloud.org/ns}group-share' => isset($p['uri']) && str_starts_with($p['uri'], 'principals/groups')
  146. ];
  147. }
  148. $this->shareCache->set((string)$resourceId, $shares);
  149. return $shares;
  150. }
  151. public function preloadShares(array $resourceIds): void {
  152. $resourceIds = array_filter($resourceIds, function (int $resourceId) {
  153. return empty($this->shareCache->get((string)$resourceId));
  154. });
  155. if (empty($resourceIds)) {
  156. return;
  157. }
  158. $rows = $this->service->getSharesForIds($resourceIds);
  159. $sharesByResource = array_fill_keys($resourceIds, []);
  160. foreach($rows as $row) {
  161. $resourceId = (int)$row['resourceid'];
  162. $p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
  163. $sharesByResource[$resourceId][] = [
  164. 'href' => "principal:{$row['principaluri']}",
  165. 'commonName' => isset($p['{DAV:}displayname']) ? (string)$p['{DAV:}displayname'] : '',
  166. 'status' => 1,
  167. 'readOnly' => (int) $row['access'] === self::ACCESS_READ,
  168. '{http://owncloud.org/ns}principal' => (string)$row['principaluri'],
  169. '{http://owncloud.org/ns}group-share' => isset($p['uri']) && str_starts_with($p['uri'], 'principals/groups')
  170. ];
  171. $this->shareCache->set((string)$resourceId, $sharesByResource[$resourceId]);
  172. }
  173. }
  174. /**
  175. * For shared resources the sharee is set in the ACL of the resource
  176. *
  177. * @param int $resourceId
  178. * @param list<array{privilege: string, principal: string, protected: bool}> $acl
  179. * @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
  180. * @return list<array{principal: string, privilege: string, protected: bool}>
  181. */
  182. public function applyShareAcl(array $shares, array $acl): array {
  183. foreach ($shares as $share) {
  184. $acl[] = [
  185. 'privilege' => '{DAV:}read',
  186. 'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
  187. 'protected' => true,
  188. ];
  189. if (!$share['readOnly']) {
  190. $acl[] = [
  191. 'privilege' => '{DAV:}write',
  192. 'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
  193. 'protected' => true,
  194. ];
  195. } elseif (in_array($this->service->getResourceType(), ['calendar','addressbook'])) {
  196. // Allow changing the properties of read only calendars,
  197. // so users can change the visibility.
  198. $acl[] = [
  199. 'privilege' => '{DAV:}write-properties',
  200. 'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
  201. 'protected' => true,
  202. ];
  203. }
  204. }
  205. return $acl;
  206. }
  207. }