1
0

Backend.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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\IDBConnection;
  33. use OCP\IGroupManager;
  34. use OCP\IUserManager;
  35. use OCP\DB\QueryBuilder\IQueryBuilder;
  36. class Backend {
  37. use TTransactional;
  38. private IDBConnection $db;
  39. private IUserManager $userManager;
  40. private IGroupManager $groupManager;
  41. private Principal $principalBackend;
  42. private string $resourceType;
  43. public const ACCESS_OWNER = 1;
  44. public const ACCESS_READ_WRITE = 2;
  45. public const ACCESS_READ = 3;
  46. public function __construct(IDBConnection $db, IUserManager $userManager, IGroupManager $groupManager, Principal $principalBackend, string $resourceType) {
  47. $this->db = $db;
  48. $this->userManager = $userManager;
  49. $this->groupManager = $groupManager;
  50. $this->principalBackend = $principalBackend;
  51. $this->resourceType = $resourceType;
  52. }
  53. /**
  54. * @param list<array{href: string, commonName: string, readOnly: bool}> $add
  55. * @param list<string> $remove
  56. */
  57. public function updateShares(IShareable $shareable, array $add, array $remove): void {
  58. $this->atomic(function () use ($shareable, $add, $remove) {
  59. foreach ($add as $element) {
  60. $principal = $this->principalBackend->findByUri($element['href'], '');
  61. if ($principal !== '') {
  62. $this->shareWith($shareable, $element);
  63. }
  64. }
  65. foreach ($remove as $element) {
  66. $principal = $this->principalBackend->findByUri($element, '');
  67. if ($principal !== '') {
  68. $this->unshare($shareable, $element);
  69. }
  70. }
  71. }, $this->db);
  72. }
  73. /**
  74. * @param array{href: string, commonName: string, readOnly: bool} $element
  75. */
  76. private function shareWith(IShareable $shareable, array $element): void {
  77. $user = $element['href'];
  78. $parts = explode(':', $user, 2);
  79. if ($parts[0] !== 'principal') {
  80. return;
  81. }
  82. // don't share with owner
  83. if ($shareable->getOwner() === $parts[1]) {
  84. return;
  85. }
  86. $principal = explode('/', $parts[1], 3);
  87. if (count($principal) !== 3 || $principal[0] !== 'principals' || !in_array($principal[1], ['users', 'groups', 'circles'], true)) {
  88. // Invalid principal
  89. return;
  90. }
  91. $principal[2] = urldecode($principal[2]);
  92. if (($principal[1] === 'users' && !$this->userManager->userExists($principal[2])) ||
  93. ($principal[1] === 'groups' && !$this->groupManager->groupExists($principal[2]))) {
  94. // User or group does not exist
  95. return;
  96. }
  97. // remove the share if it already exists
  98. $this->unshare($shareable, $element['href']);
  99. $access = self::ACCESS_READ;
  100. if (isset($element['readOnly'])) {
  101. $access = $element['readOnly'] ? self::ACCESS_READ : self::ACCESS_READ_WRITE;
  102. }
  103. $query = $this->db->getQueryBuilder();
  104. $query->insert('dav_shares')
  105. ->values([
  106. 'principaluri' => $query->createNamedParameter($parts[1]),
  107. 'type' => $query->createNamedParameter($this->resourceType),
  108. 'access' => $query->createNamedParameter($access),
  109. 'resourceid' => $query->createNamedParameter($shareable->getResourceId())
  110. ]);
  111. $query->executeStatement();
  112. }
  113. public function deleteAllShares(int $resourceId): void {
  114. $query = $this->db->getQueryBuilder();
  115. $query->delete('dav_shares')
  116. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId)))
  117. ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
  118. ->executeStatement();
  119. }
  120. public function deleteAllSharesByUser(string $principaluri): void {
  121. $query = $this->db->getQueryBuilder();
  122. $query->delete('dav_shares')
  123. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principaluri)))
  124. ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
  125. ->executeStatement();
  126. }
  127. private function unshare(IShareable $shareable, string $element): void {
  128. $parts = explode(':', $element, 2);
  129. if ($parts[0] !== 'principal') {
  130. return;
  131. }
  132. // don't share with owner
  133. if ($shareable->getOwner() === $parts[1]) {
  134. return;
  135. }
  136. $query = $this->db->getQueryBuilder();
  137. $query->delete('dav_shares')
  138. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($shareable->getResourceId())))
  139. ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
  140. ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($parts[1])))
  141. ;
  142. $query->executeStatement();
  143. }
  144. /**
  145. * Returns the list of people whom this resource is shared with.
  146. *
  147. * Every element in this array should have the following properties:
  148. * * href - Often a mailto: address
  149. * * commonName - Optional, for example a first + last name
  150. * * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
  151. * * readOnly - boolean
  152. *
  153. * @param int $resourceId
  154. * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
  155. */
  156. public function getShares(int $resourceId): array {
  157. $query = $this->db->getQueryBuilder();
  158. $result = $query->select(['principaluri', 'access'])
  159. ->from('dav_shares')
  160. ->where($query->expr()->eq('resourceid', $query->createNamedParameter($resourceId, IQueryBuilder::PARAM_INT)))
  161. ->andWhere($query->expr()->eq('type', $query->createNamedParameter($this->resourceType)))
  162. ->groupBy(['principaluri', 'access'])
  163. ->executeQuery();
  164. $shares = [];
  165. while ($row = $result->fetch()) {
  166. $p = $this->principalBackend->getPrincipalByPath($row['principaluri']);
  167. $shares[] = [
  168. 'href' => "principal:{$row['principaluri']}",
  169. 'commonName' => isset($p['{DAV:}displayname']) ? (string)$p['{DAV:}displayname'] : '',
  170. 'status' => 1,
  171. 'readOnly' => (int) $row['access'] === self::ACCESS_READ,
  172. '{http://owncloud.org/ns}principal' => (string)$row['principaluri'],
  173. '{http://owncloud.org/ns}group-share' => isset($p['uri']) ? str_starts_with($p['uri'], 'principals/groups') : false
  174. ];
  175. }
  176. return $shares;
  177. }
  178. /**
  179. * For shared resources the sharee is set in the ACL of the resource
  180. *
  181. * @param int $resourceId
  182. * @param list<array{privilege: string, principal: string, protected: bool}> $acl
  183. * @return list<array{privilege: string, principal: string, protected: bool}>
  184. */
  185. public function applyShareAcl(int $resourceId, array $acl): array {
  186. $shares = $this->getShares($resourceId);
  187. foreach ($shares as $share) {
  188. $acl[] = [
  189. 'privilege' => '{DAV:}read',
  190. 'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
  191. 'protected' => true,
  192. ];
  193. if (!$share['readOnly']) {
  194. $acl[] = [
  195. 'privilege' => '{DAV:}write',
  196. 'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
  197. 'protected' => true,
  198. ];
  199. } elseif ($this->resourceType === 'calendar') {
  200. // Allow changing the properties of read only calendars,
  201. // so users can change the visibility.
  202. $acl[] = [
  203. 'privilege' => '{DAV:}write-properties',
  204. 'principal' => $share['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}principal'],
  205. 'protected' => true,
  206. ];
  207. }
  208. }
  209. return $acl;
  210. }
  211. }