1
0

ShareAPIController.php 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033
  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\Files_Sharing\Controller;
  9. use Exception;
  10. use OC\Files\FileInfo;
  11. use OC\Files\Storage\Wrapper\Wrapper;
  12. use OCA\Files\Helper;
  13. use OCA\Files_Sharing\Exceptions\SharingRightsException;
  14. use OCA\Files_Sharing\External\Storage;
  15. use OCA\Files_Sharing\ResponseDefinitions;
  16. use OCA\Files_Sharing\SharedStorage;
  17. use OCP\App\IAppManager;
  18. use OCP\AppFramework\Http;
  19. use OCP\AppFramework\Http\DataResponse;
  20. use OCP\AppFramework\OCS\OCSBadRequestException;
  21. use OCP\AppFramework\OCS\OCSException;
  22. use OCP\AppFramework\OCS\OCSForbiddenException;
  23. use OCP\AppFramework\OCS\OCSNotFoundException;
  24. use OCP\AppFramework\OCSController;
  25. use OCP\AppFramework\QueryException;
  26. use OCP\Constants;
  27. use OCP\Files\Folder;
  28. use OCP\Files\InvalidPathException;
  29. use OCP\Files\IRootFolder;
  30. use OCP\Files\Node;
  31. use OCP\Files\NotFoundException;
  32. use OCP\IConfig;
  33. use OCP\IDateTimeZone;
  34. use OCP\IGroupManager;
  35. use OCP\IL10N;
  36. use OCP\IPreview;
  37. use OCP\IRequest;
  38. use OCP\IURLGenerator;
  39. use OCP\IUserManager;
  40. use OCP\Lock\ILockingProvider;
  41. use OCP\Lock\LockedException;
  42. use OCP\Server;
  43. use OCP\Share\Exceptions\GenericShareException;
  44. use OCP\Share\Exceptions\ShareNotFound;
  45. use OCP\Share\IManager;
  46. use OCP\Share\IShare;
  47. use OCP\UserStatus\IManager as IUserStatusManager;
  48. use Psr\Container\ContainerExceptionInterface;
  49. use Psr\Container\ContainerInterface;
  50. use Psr\Log\LoggerInterface;
  51. /**
  52. * @package OCA\Files_Sharing\API
  53. *
  54. * @psalm-import-type Files_SharingShare from ResponseDefinitions
  55. */
  56. class ShareAPIController extends OCSController {
  57. private ?Node $lockedNode = null;
  58. private string $currentUser;
  59. /**
  60. * Share20OCS constructor.
  61. */
  62. public function __construct(
  63. string $appName,
  64. IRequest $request,
  65. private IManager $shareManager,
  66. private IGroupManager $groupManager,
  67. private IUserManager $userManager,
  68. private IRootFolder $rootFolder,
  69. private IURLGenerator $urlGenerator,
  70. private IL10N $l,
  71. private IConfig $config,
  72. private IAppManager $appManager,
  73. private ContainerInterface $serverContainer,
  74. private IUserStatusManager $userStatusManager,
  75. private IPreview $previewManager,
  76. private IDateTimeZone $dateTimeZone,
  77. private LoggerInterface $logger,
  78. ?string $userId = null
  79. ) {
  80. parent::__construct($appName, $request);
  81. $this->currentUser = $userId;
  82. }
  83. /**
  84. * Convert an IShare to an array for OCS output
  85. *
  86. * @param \OCP\Share\IShare $share
  87. * @param Node|null $recipientNode
  88. * @return Files_SharingShare
  89. * @throws NotFoundException In case the node can't be resolved.
  90. *
  91. * @suppress PhanUndeclaredClassMethod
  92. */
  93. protected function formatShare(IShare $share, ?Node $recipientNode = null): array {
  94. $sharedBy = $this->userManager->get($share->getSharedBy());
  95. $shareOwner = $this->userManager->get($share->getShareOwner());
  96. $isOwnShare = false;
  97. if ($shareOwner !== null) {
  98. $isOwnShare = $shareOwner->getUID() === $this->currentUser;
  99. }
  100. $result = [
  101. 'id' => $share->getId(),
  102. 'share_type' => $share->getShareType(),
  103. 'uid_owner' => $share->getSharedBy(),
  104. 'displayname_owner' => $sharedBy !== null ? $sharedBy->getDisplayName() : $share->getSharedBy(),
  105. // recipient permissions
  106. 'permissions' => $share->getPermissions(),
  107. // current user permissions on this share
  108. 'can_edit' => $this->canEditShare($share),
  109. 'can_delete' => $this->canDeleteShare($share),
  110. 'stime' => $share->getShareTime()->getTimestamp(),
  111. 'parent' => null,
  112. 'expiration' => null,
  113. 'token' => null,
  114. 'uid_file_owner' => $share->getShareOwner(),
  115. 'note' => $share->getNote(),
  116. 'label' => $share->getLabel(),
  117. 'displayname_file_owner' => $shareOwner !== null ? $shareOwner->getDisplayName() : $share->getShareOwner(),
  118. ];
  119. $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
  120. if ($recipientNode) {
  121. $node = $recipientNode;
  122. } else {
  123. $node = $userFolder->getFirstNodeById($share->getNodeId());
  124. if (!$node) {
  125. // fallback to guessing the path
  126. $node = $userFolder->get($share->getTarget());
  127. if ($node === null || $share->getTarget() === '') {
  128. throw new NotFoundException();
  129. }
  130. }
  131. }
  132. $result['path'] = $userFolder->getRelativePath($node->getPath());
  133. if ($node instanceof Folder) {
  134. $result['item_type'] = 'folder';
  135. } else {
  136. $result['item_type'] = 'file';
  137. }
  138. // Get the original node permission if the share owner is the current user
  139. if ($isOwnShare) {
  140. $result['item_permissions'] = $node->getPermissions();
  141. }
  142. $result['mimetype'] = $node->getMimetype();
  143. $result['has_preview'] = $this->previewManager->isAvailable($node);
  144. $result['storage_id'] = $node->getStorage()->getId();
  145. $result['storage'] = $node->getStorage()->getCache()->getNumericStorageId();
  146. $result['item_source'] = $node->getId();
  147. $result['file_source'] = $node->getId();
  148. $result['file_parent'] = $node->getParent()->getId();
  149. $result['file_target'] = $share->getTarget();
  150. $result['item_size'] = $node->getSize();
  151. $result['item_mtime'] = $node->getMTime();
  152. $expiration = $share->getExpirationDate();
  153. if ($expiration !== null) {
  154. $expiration->setTimezone($this->dateTimeZone->getTimeZone());
  155. $result['expiration'] = $expiration->format('Y-m-d 00:00:00');
  156. }
  157. if ($share->getShareType() === IShare::TYPE_USER) {
  158. $sharedWith = $this->userManager->get($share->getSharedWith());
  159. $result['share_with'] = $share->getSharedWith();
  160. $result['share_with_displayname'] = $sharedWith !== null ? $sharedWith->getDisplayName() : $share->getSharedWith();
  161. $result['share_with_displayname_unique'] = $sharedWith !== null ? (
  162. !empty($sharedWith->getSystemEMailAddress()) ? $sharedWith->getSystemEMailAddress() : $sharedWith->getUID()
  163. ) : $share->getSharedWith();
  164. $userStatuses = $this->userStatusManager->getUserStatuses([$share->getSharedWith()]);
  165. $userStatus = array_shift($userStatuses);
  166. if ($userStatus) {
  167. $result['status'] = [
  168. 'status' => $userStatus->getStatus(),
  169. 'message' => $userStatus->getMessage(),
  170. 'icon' => $userStatus->getIcon(),
  171. 'clearAt' => $userStatus->getClearAt()
  172. ? (int)$userStatus->getClearAt()->format('U')
  173. : null,
  174. ];
  175. }
  176. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  177. $group = $this->groupManager->get($share->getSharedWith());
  178. $result['share_with'] = $share->getSharedWith();
  179. $result['share_with_displayname'] = $group !== null ? $group->getDisplayName() : $share->getSharedWith();
  180. } elseif ($share->getShareType() === IShare::TYPE_LINK) {
  181. // "share_with" and "share_with_displayname" for passwords of link
  182. // shares was deprecated in Nextcloud 15, use "password" instead.
  183. $result['share_with'] = $share->getPassword();
  184. $result['share_with_displayname'] = '(' . $this->l->t('Shared link') . ')';
  185. $result['password'] = $share->getPassword();
  186. $result['send_password_by_talk'] = $share->getSendPasswordByTalk();
  187. $result['token'] = $share->getToken();
  188. $result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]);
  189. } elseif ($share->getShareType() === IShare::TYPE_REMOTE) {
  190. $result['share_with'] = $share->getSharedWith();
  191. $result['share_with_displayname'] = $this->getCachedFederatedDisplayName($share->getSharedWith());
  192. $result['token'] = $share->getToken();
  193. } elseif ($share->getShareType() === IShare::TYPE_REMOTE_GROUP) {
  194. $result['share_with'] = $share->getSharedWith();
  195. $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'CLOUD');
  196. $result['token'] = $share->getToken();
  197. } elseif ($share->getShareType() === IShare::TYPE_EMAIL) {
  198. $result['share_with'] = $share->getSharedWith();
  199. $result['password'] = $share->getPassword();
  200. $result['password_expiration_time'] = $share->getPasswordExpirationTime() !== null ? $share->getPasswordExpirationTime()->format(\DateTime::ATOM) : null;
  201. $result['send_password_by_talk'] = $share->getSendPasswordByTalk();
  202. $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'EMAIL');
  203. $result['token'] = $share->getToken();
  204. } elseif ($share->getShareType() === IShare::TYPE_CIRCLE) {
  205. // getSharedWith() returns either "name (type, owner)" or
  206. // "name (type, owner) [id]", depending on the Circles app version.
  207. $hasCircleId = (substr($share->getSharedWith(), -1) === ']');
  208. $result['share_with_displayname'] = $share->getSharedWithDisplayName();
  209. if (empty($result['share_with_displayname'])) {
  210. $displayNameLength = ($hasCircleId ? strrpos($share->getSharedWith(), ' ') : strlen($share->getSharedWith()));
  211. $result['share_with_displayname'] = substr($share->getSharedWith(), 0, $displayNameLength);
  212. }
  213. $result['share_with_avatar'] = $share->getSharedWithAvatar();
  214. $shareWithStart = ($hasCircleId ? strrpos($share->getSharedWith(), '[') + 1 : 0);
  215. $shareWithLength = ($hasCircleId ? -1 : strpos($share->getSharedWith(), ' '));
  216. if ($shareWithLength === false) {
  217. $result['share_with'] = substr($share->getSharedWith(), $shareWithStart);
  218. } else {
  219. $result['share_with'] = substr($share->getSharedWith(), $shareWithStart, $shareWithLength);
  220. }
  221. } elseif ($share->getShareType() === IShare::TYPE_ROOM) {
  222. $result['share_with'] = $share->getSharedWith();
  223. $result['share_with_displayname'] = '';
  224. try {
  225. /** @var array{share_with_displayname: string, share_with_link: string, share_with?: string, token?: string} $roomShare */
  226. $roomShare = $this->getRoomShareHelper()->formatShare($share);
  227. $result = array_merge($result, $roomShare);
  228. } catch (QueryException $e) {
  229. }
  230. } elseif ($share->getShareType() === IShare::TYPE_DECK) {
  231. $result['share_with'] = $share->getSharedWith();
  232. $result['share_with_displayname'] = '';
  233. try {
  234. /** @var array{share_with: string, share_with_displayname: string, share_with_link: string} $deckShare */
  235. $deckShare = $this->getDeckShareHelper()->formatShare($share);
  236. $result = array_merge($result, $deckShare);
  237. } catch (QueryException $e) {
  238. }
  239. } elseif ($share->getShareType() === IShare::TYPE_SCIENCEMESH) {
  240. $result['share_with'] = $share->getSharedWith();
  241. $result['share_with_displayname'] = '';
  242. try {
  243. /** @var array{share_with: string, share_with_displayname: string, token: string} $scienceMeshShare */
  244. $scienceMeshShare = $this->getSciencemeshShareHelper()->formatShare($share);
  245. $result = array_merge($result, $scienceMeshShare);
  246. } catch (QueryException $e) {
  247. }
  248. }
  249. $result['mail_send'] = $share->getMailSend() ? 1 : 0;
  250. $result['hide_download'] = $share->getHideDownload() ? 1 : 0;
  251. $result['attributes'] = null;
  252. if ($attributes = $share->getAttributes()) {
  253. $result['attributes'] = (string)\json_encode($attributes->toArray());
  254. }
  255. return $result;
  256. }
  257. /**
  258. * Check if one of the users address books knows the exact property, if
  259. * not we return the full name.
  260. *
  261. * @param string $query
  262. * @param string $property
  263. * @return string
  264. */
  265. private function getDisplayNameFromAddressBook(string $query, string $property): string {
  266. // FIXME: If we inject the contacts manager it gets initialized before any address books are registered
  267. try {
  268. $result = \OC::$server->getContactsManager()->search($query, [$property], [
  269. 'limit' => 1,
  270. 'enumeration' => false,
  271. 'strict_search' => true,
  272. ]);
  273. } catch (Exception $e) {
  274. $this->logger->error(
  275. $e->getMessage(),
  276. ['exception' => $e]
  277. );
  278. return $query;
  279. }
  280. foreach ($result as $r) {
  281. foreach ($r[$property] as $value) {
  282. if ($value === $query && $r['FN']) {
  283. return $r['FN'];
  284. }
  285. }
  286. }
  287. return $query;
  288. }
  289. /**
  290. * @param array $shares
  291. * @param array|null $updatedDisplayName
  292. *
  293. * @return array
  294. */
  295. private function fixMissingDisplayName(array $shares, ?array $updatedDisplayName = null): array {
  296. $userIds = $updated = [];
  297. foreach ($shares as $share) {
  298. // share is federated and share have no display name yet
  299. if ($share['share_type'] === IShare::TYPE_REMOTE
  300. && ($share['share_with'] ?? '') !== ''
  301. && ($share['share_with_displayname'] ?? '') === '') {
  302. $userIds[] = $userId = $share['share_with'];
  303. if ($updatedDisplayName !== null && array_key_exists($userId, $updatedDisplayName)) {
  304. $share['share_with_displayname'] = $updatedDisplayName[$userId];
  305. }
  306. }
  307. // prepping userIds with displayName to be updated
  308. $updated[] = $share;
  309. }
  310. // if $updatedDisplayName is not null, it means we should have already fixed displayNames of the shares
  311. if ($updatedDisplayName !== null) {
  312. return $updated;
  313. }
  314. // get displayName for the generated list of userId with no displayName
  315. $displayNames = $this->retrieveFederatedDisplayName($userIds);
  316. // if no displayName are updated, we exit
  317. if (empty($displayNames)) {
  318. return $updated;
  319. }
  320. // let's fix missing display name and returns all shares
  321. return $this->fixMissingDisplayName($shares, $displayNames);
  322. }
  323. /**
  324. * get displayName of a list of userIds from the lookup-server; through the globalsiteselector app.
  325. * returns an array with userIds as keys and displayName as values.
  326. *
  327. * @param array $userIds
  328. * @param bool $cacheOnly - do not reach LUS, get data from cache.
  329. *
  330. * @return array
  331. * @throws ContainerExceptionInterface
  332. */
  333. private function retrieveFederatedDisplayName(array $userIds, bool $cacheOnly = false): array {
  334. // check if gss is enabled and available
  335. if (count($userIds) === 0
  336. || !$this->appManager->isInstalled('globalsiteselector')
  337. || !class_exists('\OCA\GlobalSiteSelector\Service\SlaveService')) {
  338. return [];
  339. }
  340. try {
  341. $slaveService = Server::get(\OCA\GlobalSiteSelector\Service\SlaveService::class);
  342. } catch (\Throwable $e) {
  343. $this->logger->error(
  344. $e->getMessage(),
  345. ['exception' => $e]
  346. );
  347. return [];
  348. }
  349. return $slaveService->getUsersDisplayName($userIds, $cacheOnly);
  350. }
  351. /**
  352. * retrieve displayName from cache if available (should be used on federated shares)
  353. * if not available in cache/lus, try for get from address-book, else returns empty string.
  354. *
  355. * @param string $userId
  356. * @param bool $cacheOnly if true will not reach the lus but will only get data from cache
  357. *
  358. * @return string
  359. */
  360. private function getCachedFederatedDisplayName(string $userId, bool $cacheOnly = true): string {
  361. $details = $this->retrieveFederatedDisplayName([$userId], $cacheOnly);
  362. if (array_key_exists($userId, $details)) {
  363. return $details[$userId];
  364. }
  365. $displayName = $this->getDisplayNameFromAddressBook($userId, 'CLOUD');
  366. return ($displayName === $userId) ? '' : $displayName;
  367. }
  368. /**
  369. * @NoAdminRequired
  370. *
  371. * Get a specific share by id
  372. *
  373. * @param string $id ID of the share
  374. * @param bool $include_tags Include tags in the share
  375. * @return DataResponse<Http::STATUS_OK, Files_SharingShare, array{}>
  376. * @throws OCSNotFoundException Share not found
  377. *
  378. * 200: Share returned
  379. */
  380. public function getShare(string $id, bool $include_tags = false): DataResponse {
  381. try {
  382. $share = $this->getShareById($id);
  383. } catch (ShareNotFound $e) {
  384. throw new OCSNotFoundException($this->l->t('Wrong share ID, share does not exist'));
  385. }
  386. try {
  387. if ($this->canAccessShare($share)) {
  388. $share = $this->formatShare($share);
  389. if ($include_tags) {
  390. $share = Helper::populateTags([$share], 'file_source', \OC::$server->getTagManager());
  391. } else {
  392. $share = [$share];
  393. }
  394. return new DataResponse($share);
  395. }
  396. } catch (NotFoundException $e) {
  397. // Fall through
  398. }
  399. throw new OCSNotFoundException($this->l->t('Wrong share ID, share does not exist'));
  400. }
  401. /**
  402. * @NoAdminRequired
  403. *
  404. * Delete a share
  405. *
  406. * @param string $id ID of the share
  407. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  408. * @throws OCSNotFoundException Share not found
  409. * @throws OCSForbiddenException Missing permissions to delete the share
  410. *
  411. * 200: Share deleted successfully
  412. */
  413. public function deleteShare(string $id): DataResponse {
  414. try {
  415. $share = $this->getShareById($id);
  416. } catch (ShareNotFound $e) {
  417. throw new OCSNotFoundException($this->l->t('Wrong share ID, share does not exist'));
  418. }
  419. try {
  420. $this->lock($share->getNode());
  421. } catch (LockedException $e) {
  422. throw new OCSNotFoundException($this->l->t('Could not delete share'));
  423. }
  424. if (!$this->canAccessShare($share)) {
  425. throw new OCSNotFoundException($this->l->t('Wrong share ID, share does not exist'));
  426. }
  427. // if it's a group share or a room share
  428. // we don't delete the share, but only the
  429. // mount point. Allowing it to be restored
  430. // from the deleted shares
  431. if ($this->canDeleteShareFromSelf($share)) {
  432. $this->shareManager->deleteFromSelf($share, $this->currentUser);
  433. } else {
  434. if (!$this->canDeleteShare($share)) {
  435. throw new OCSForbiddenException($this->l->t('Could not delete share'));
  436. }
  437. $this->shareManager->deleteShare($share);
  438. }
  439. return new DataResponse();
  440. }
  441. /**
  442. * @NoAdminRequired
  443. *
  444. * Create a share
  445. *
  446. * @param string|null $path Path of the share
  447. * @param int|null $permissions Permissions for the share
  448. * @param int $shareType Type of the share
  449. * @param string|null $shareWith The entity this should be shared with
  450. * @param string $publicUpload If public uploading is allowed
  451. * @param string $password Password for the share
  452. * @param string|null $sendPasswordByTalk Send the password for the share over Talk
  453. * @param ?string $expireDate The expiry date of the share in the user's timezone (UTC) at 00:00.
  454. * If $expireDate is not supplied or set to `null`, the system default will be used.
  455. * @param string $note Note for the share
  456. * @param string $label Label for the share (only used in link and email)
  457. * @param string|null $attributes Additional attributes for the share
  458. *
  459. * @return DataResponse<Http::STATUS_OK, Files_SharingShare, array{}>
  460. * @throws OCSBadRequestException Unknown share type
  461. * @throws OCSException
  462. * @throws OCSForbiddenException Creating the share is not allowed
  463. * @throws OCSNotFoundException Creating the share failed
  464. * @suppress PhanUndeclaredClassMethod
  465. *
  466. * 200: Share created
  467. */
  468. public function createShare(
  469. ?string $path = null,
  470. ?int $permissions = null,
  471. int $shareType = -1,
  472. ?string $shareWith = null,
  473. string $publicUpload = 'false',
  474. string $password = '',
  475. ?string $sendPasswordByTalk = null,
  476. ?string $expireDate = null,
  477. string $note = '',
  478. string $label = '',
  479. ?string $attributes = null
  480. ): DataResponse {
  481. $share = $this->shareManager->newShare();
  482. if ($permissions === null) {
  483. if ($shareType === IShare::TYPE_LINK
  484. || $shareType === IShare::TYPE_EMAIL) {
  485. // to keep legacy default behaviour, we ignore the setting below for link shares
  486. $permissions = Constants::PERMISSION_READ;
  487. } else {
  488. $permissions = (int)$this->config->getAppValue('core', 'shareapi_default_permissions', (string)Constants::PERMISSION_ALL);
  489. }
  490. }
  491. // Verify path
  492. if ($path === null) {
  493. throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
  494. }
  495. $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
  496. try {
  497. /** @var \OC\Files\Node\Node $node */
  498. $node = $userFolder->get($path);
  499. } catch (NotFoundException $e) {
  500. throw new OCSNotFoundException($this->l->t('Wrong path, file/folder does not exist'));
  501. }
  502. // a user can have access to a file through different paths, with differing permissions
  503. // combine all permissions to determine if the user can share this file
  504. $nodes = $userFolder->getById($node->getId());
  505. foreach ($nodes as $nodeById) {
  506. /** @var FileInfo $fileInfo */
  507. $fileInfo = $node->getFileInfo();
  508. $fileInfo['permissions'] |= $nodeById->getPermissions();
  509. }
  510. $share->setNode($node);
  511. try {
  512. $this->lock($share->getNode());
  513. } catch (LockedException $e) {
  514. throw new OCSNotFoundException($this->l->t('Could not create share'));
  515. }
  516. if ($permissions < 0 || $permissions > Constants::PERMISSION_ALL) {
  517. throw new OCSNotFoundException($this->l->t('Invalid permissions'));
  518. }
  519. // Shares always require read permissions
  520. $permissions |= Constants::PERMISSION_READ;
  521. if ($node instanceof \OCP\Files\File) {
  522. // Single file shares should never have delete or create permissions
  523. $permissions &= ~Constants::PERMISSION_DELETE;
  524. $permissions &= ~Constants::PERMISSION_CREATE;
  525. }
  526. /**
  527. * Hack for https://github.com/owncloud/core/issues/22587
  528. * We check the permissions via webdav. But the permissions of the mount point
  529. * do not equal the share permissions. Here we fix that for federated mounts.
  530. */
  531. if ($node->getStorage()->instanceOfStorage(Storage::class)) {
  532. $permissions &= ~($permissions & ~$node->getPermissions());
  533. }
  534. if ($attributes !== null) {
  535. $share = $this->setShareAttributes($share, $attributes);
  536. }
  537. //Expire date
  538. if ($expireDate !== null) {
  539. if ($expireDate !== '') {
  540. try {
  541. $expireDateTime = $this->parseDate($expireDate);
  542. $share->setExpirationDate($expireDateTime);
  543. } catch (\Exception $e) {
  544. throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
  545. }
  546. } else {
  547. // Client sent empty string for expire date.
  548. // Set noExpirationDate to true so overwrite is prevented.
  549. $share->setNoExpirationDate(true);
  550. }
  551. }
  552. $share->setSharedBy($this->currentUser);
  553. $this->checkInheritedAttributes($share);
  554. if ($shareType === IShare::TYPE_USER) {
  555. // Valid user is required to share
  556. if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
  557. throw new OCSNotFoundException($this->l->t('Please specify a valid account to share with'));
  558. }
  559. $share->setSharedWith($shareWith);
  560. $share->setPermissions($permissions);
  561. } elseif ($shareType === IShare::TYPE_GROUP) {
  562. if (!$this->shareManager->allowGroupSharing()) {
  563. throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
  564. }
  565. // Valid group is required to share
  566. if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
  567. throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
  568. }
  569. $share->setSharedWith($shareWith);
  570. $share->setPermissions($permissions);
  571. } elseif ($shareType === IShare::TYPE_LINK
  572. || $shareType === IShare::TYPE_EMAIL) {
  573. // Can we even share links?
  574. if (!$this->shareManager->shareApiAllowLinks()) {
  575. throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
  576. }
  577. if ($publicUpload === 'true') {
  578. // Check if public upload is allowed
  579. if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
  580. throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
  581. }
  582. // Public upload can only be set for folders
  583. if ($node instanceof \OCP\Files\File) {
  584. throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
  585. }
  586. $permissions = Constants::PERMISSION_READ |
  587. Constants::PERMISSION_CREATE |
  588. Constants::PERMISSION_UPDATE |
  589. Constants::PERMISSION_DELETE;
  590. }
  591. // TODO: It might make sense to have a dedicated setting to allow/deny converting link shares into federated ones
  592. if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
  593. $permissions |= Constants::PERMISSION_SHARE;
  594. }
  595. $share->setPermissions($permissions);
  596. // Set password
  597. if ($password !== '') {
  598. $share->setPassword($password);
  599. }
  600. // Only share by mail have a recipient
  601. if (is_string($shareWith) && $shareType === IShare::TYPE_EMAIL) {
  602. $share->setSharedWith($shareWith);
  603. }
  604. // If we have a label, use it
  605. if (!empty($label)) {
  606. $share->setLabel($label);
  607. }
  608. if ($sendPasswordByTalk === 'true') {
  609. if (!$this->appManager->isEnabledForUser('spreed')) {
  610. throw new OCSForbiddenException($this->l->t('Sharing %s sending the password by Nextcloud Talk failed because Nextcloud Talk is not enabled', [$node->getPath()]));
  611. }
  612. $share->setSendPasswordByTalk(true);
  613. }
  614. } elseif ($shareType === IShare::TYPE_REMOTE) {
  615. if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
  616. throw new OCSForbiddenException($this->l->t('Sharing %1$s failed because the back end does not allow shares from type %2$s', [$node->getPath(), $shareType]));
  617. }
  618. if ($shareWith === null) {
  619. throw new OCSNotFoundException($this->l->t('Please specify a valid federated account ID'));
  620. }
  621. $share->setSharedWith($shareWith);
  622. $share->setPermissions($permissions);
  623. $share->setSharedWithDisplayName($this->getCachedFederatedDisplayName($shareWith, false));
  624. } elseif ($shareType === IShare::TYPE_REMOTE_GROUP) {
  625. if (!$this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
  626. throw new OCSForbiddenException($this->l->t('Sharing %1$s failed because the back end does not allow shares from type %2$s', [$node->getPath(), $shareType]));
  627. }
  628. if ($shareWith === null) {
  629. throw new OCSNotFoundException($this->l->t('Please specify a valid federated group ID'));
  630. }
  631. $share->setSharedWith($shareWith);
  632. $share->setPermissions($permissions);
  633. } elseif ($shareType === IShare::TYPE_CIRCLE) {
  634. if (!\OC::$server->getAppManager()->isEnabledForUser('circles') || !class_exists('\OCA\Circles\ShareByCircleProvider')) {
  635. throw new OCSNotFoundException($this->l->t('You cannot share to a Circle if the app is not enabled'));
  636. }
  637. $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($shareWith);
  638. // Valid circle is required to share
  639. if ($circle === null) {
  640. throw new OCSNotFoundException($this->l->t('Please specify a valid circle'));
  641. }
  642. $share->setSharedWith($shareWith);
  643. $share->setPermissions($permissions);
  644. } elseif ($shareType === IShare::TYPE_ROOM) {
  645. try {
  646. $this->getRoomShareHelper()->createShare($share, $shareWith, $permissions, $expireDate ?? '');
  647. } catch (QueryException $e) {
  648. throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not support room shares', [$node->getPath()]));
  649. }
  650. } elseif ($shareType === IShare::TYPE_DECK) {
  651. try {
  652. $this->getDeckShareHelper()->createShare($share, $shareWith, $permissions, $expireDate ?? '');
  653. } catch (QueryException $e) {
  654. throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not support room shares', [$node->getPath()]));
  655. }
  656. } elseif ($shareType === IShare::TYPE_SCIENCEMESH) {
  657. try {
  658. $this->getSciencemeshShareHelper()->createShare($share, $shareWith, $permissions, $expireDate ?? '');
  659. } catch (QueryException $e) {
  660. throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not support ScienceMesh shares', [$node->getPath()]));
  661. }
  662. } else {
  663. throw new OCSBadRequestException($this->l->t('Unknown share type'));
  664. }
  665. $share->setShareType($shareType);
  666. if ($note !== '') {
  667. $share->setNote($note);
  668. }
  669. try {
  670. $share = $this->shareManager->createShare($share);
  671. } catch (GenericShareException $e) {
  672. $this->logger->error($e->getMessage(), ['exception' => $e]);
  673. $code = $e->getCode() === 0 ? 403 : $e->getCode();
  674. throw new OCSException($e->getHint(), $code);
  675. } catch (\Exception $e) {
  676. $this->logger->error($e->getMessage(), ['exception' => $e]);
  677. throw new OCSForbiddenException($e->getMessage(), $e);
  678. }
  679. $output = $this->formatShare($share);
  680. return new DataResponse($output);
  681. }
  682. /**
  683. * @param null|Node $node
  684. * @param boolean $includeTags
  685. *
  686. * @return Files_SharingShare[]
  687. */
  688. private function getSharedWithMe($node, bool $includeTags): array {
  689. $userShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_USER, $node, -1, 0);
  690. $groupShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_GROUP, $node, -1, 0);
  691. $circleShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_CIRCLE, $node, -1, 0);
  692. $roomShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_ROOM, $node, -1, 0);
  693. $deckShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_DECK, $node, -1, 0);
  694. $sciencemeshShares = $this->shareManager->getSharedWith($this->currentUser, IShare::TYPE_SCIENCEMESH, $node, -1, 0);
  695. $shares = array_merge($userShares, $groupShares, $circleShares, $roomShares, $deckShares, $sciencemeshShares);
  696. $filteredShares = array_filter($shares, function (IShare $share) {
  697. return $share->getShareOwner() !== $this->currentUser;
  698. });
  699. $formatted = [];
  700. foreach ($filteredShares as $share) {
  701. if ($this->canAccessShare($share)) {
  702. try {
  703. $formatted[] = $this->formatShare($share);
  704. } catch (NotFoundException $e) {
  705. // Ignore this share
  706. }
  707. }
  708. }
  709. if ($includeTags) {
  710. $formatted = Helper::populateTags($formatted, 'file_source', \OC::$server->getTagManager());
  711. }
  712. return $formatted;
  713. }
  714. /**
  715. * @param \OCP\Files\Node $folder
  716. *
  717. * @return Files_SharingShare[]
  718. * @throws OCSBadRequestException
  719. * @throws NotFoundException
  720. */
  721. private function getSharesInDir(Node $folder): array {
  722. if (!($folder instanceof \OCP\Files\Folder)) {
  723. throw new OCSBadRequestException($this->l->t('Not a directory'));
  724. }
  725. $nodes = $folder->getDirectoryListing();
  726. /** @var \OCP\Share\IShare[] $shares */
  727. $shares = array_reduce($nodes, function ($carry, $node) {
  728. $carry = array_merge($carry, $this->getAllShares($node, true));
  729. return $carry;
  730. }, []);
  731. // filter out duplicate shares
  732. $known = [];
  733. $formatted = $miniFormatted = [];
  734. $resharingRight = false;
  735. $known = [];
  736. foreach ($shares as $share) {
  737. if (in_array($share->getId(), $known) || $share->getSharedWith() === $this->currentUser) {
  738. continue;
  739. }
  740. try {
  741. $format = $this->formatShare($share);
  742. $known[] = $share->getId();
  743. $formatted[] = $format;
  744. if ($share->getSharedBy() === $this->currentUser) {
  745. $miniFormatted[] = $format;
  746. }
  747. if (!$resharingRight && $this->shareProviderResharingRights($this->currentUser, $share, $folder)) {
  748. $resharingRight = true;
  749. }
  750. } catch (\Exception $e) {
  751. //Ignore this share
  752. }
  753. }
  754. if (!$resharingRight) {
  755. $formatted = $miniFormatted;
  756. }
  757. return $formatted;
  758. }
  759. /**
  760. * @NoAdminRequired
  761. *
  762. * Get shares of the current user
  763. *
  764. * @param string $shared_with_me Only get shares with the current user
  765. * @param string $reshares Only get shares by the current user and reshares
  766. * @param string $subfiles Only get all shares in a folder
  767. * @param string $path Get shares for a specific path
  768. * @param string $include_tags Include tags in the share
  769. *
  770. * @return DataResponse<Http::STATUS_OK, Files_SharingShare[], array{}>
  771. * @throws OCSNotFoundException The folder was not found or is inaccessible
  772. *
  773. * 200: Shares returned
  774. */
  775. public function getShares(
  776. string $shared_with_me = 'false',
  777. string $reshares = 'false',
  778. string $subfiles = 'false',
  779. string $path = '',
  780. string $include_tags = 'false'
  781. ): DataResponse {
  782. $node = null;
  783. if ($path !== '') {
  784. $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
  785. try {
  786. $node = $userFolder->get($path);
  787. $this->lock($node);
  788. } catch (NotFoundException $e) {
  789. throw new OCSNotFoundException(
  790. $this->l->t('Wrong path, file/folder does not exist')
  791. );
  792. } catch (LockedException $e) {
  793. throw new OCSNotFoundException($this->l->t('Could not lock node'));
  794. }
  795. }
  796. $shares = $this->getFormattedShares(
  797. $this->currentUser,
  798. $node,
  799. ($shared_with_me === 'true'),
  800. ($reshares === 'true'),
  801. ($subfiles === 'true'),
  802. ($include_tags === 'true')
  803. );
  804. return new DataResponse($shares);
  805. }
  806. /**
  807. * @param string $viewer
  808. * @param Node $node
  809. * @param bool $sharedWithMe
  810. * @param bool $reShares
  811. * @param bool $subFiles
  812. * @param bool $includeTags
  813. *
  814. * @return Files_SharingShare[]
  815. * @throws NotFoundException
  816. * @throws OCSBadRequestException
  817. */
  818. private function getFormattedShares(
  819. string $viewer,
  820. $node = null,
  821. bool $sharedWithMe = false,
  822. bool $reShares = false,
  823. bool $subFiles = false,
  824. bool $includeTags = false
  825. ): array {
  826. if ($sharedWithMe) {
  827. return $this->getSharedWithMe($node, $includeTags);
  828. }
  829. if ($subFiles) {
  830. return $this->getSharesInDir($node);
  831. }
  832. $shares = $this->getSharesFromNode($viewer, $node, $reShares);
  833. $known = $formatted = $miniFormatted = [];
  834. $resharingRight = false;
  835. foreach ($shares as $share) {
  836. try {
  837. $share->getNode();
  838. } catch (NotFoundException $e) {
  839. /*
  840. * Ignore shares where we can't get the node
  841. * For example deleted shares
  842. */
  843. continue;
  844. }
  845. if (in_array($share->getId(), $known)
  846. || ($share->getSharedWith() === $this->currentUser && $share->getShareType() === IShare::TYPE_USER)) {
  847. continue;
  848. }
  849. $known[] = $share->getId();
  850. try {
  851. /** @var IShare $share */
  852. $format = $this->formatShare($share, $node);
  853. $formatted[] = $format;
  854. // let's also build a list of shares created
  855. // by the current user only, in case
  856. // there is no resharing rights
  857. if ($share->getSharedBy() === $this->currentUser) {
  858. $miniFormatted[] = $format;
  859. }
  860. // check if one of those share is shared with me
  861. // and if I have resharing rights on it
  862. if (!$resharingRight && $this->shareProviderResharingRights($this->currentUser, $share, $node)) {
  863. $resharingRight = true;
  864. }
  865. } catch (InvalidPathException | NotFoundException $e) {
  866. }
  867. }
  868. if (!$resharingRight) {
  869. $formatted = $miniFormatted;
  870. }
  871. // fix eventual missing display name from federated shares
  872. $formatted = $this->fixMissingDisplayName($formatted);
  873. if ($includeTags) {
  874. $formatted =
  875. Helper::populateTags($formatted, 'file_source', \OC::$server->getTagManager());
  876. }
  877. return $formatted;
  878. }
  879. /**
  880. * @NoAdminRequired
  881. *
  882. * Get all shares relative to a file, including parent folders shares rights
  883. *
  884. * @param string $path Path all shares will be relative to
  885. *
  886. * @return DataResponse<Http::STATUS_OK, Files_SharingShare[], array{}>
  887. * @throws InvalidPathException
  888. * @throws NotFoundException
  889. * @throws OCSNotFoundException The given path is invalid
  890. * @throws SharingRightsException
  891. *
  892. * 200: Shares returned
  893. */
  894. public function getInheritedShares(string $path): DataResponse {
  895. // get Node from (string) path.
  896. $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
  897. try {
  898. $node = $userFolder->get($path);
  899. $this->lock($node);
  900. } catch (\OCP\Files\NotFoundException $e) {
  901. throw new OCSNotFoundException($this->l->t('Wrong path, file/folder does not exist'));
  902. } catch (LockedException $e) {
  903. throw new OCSNotFoundException($this->l->t('Could not lock path'));
  904. }
  905. if (!($node->getPermissions() & Constants::PERMISSION_SHARE)) {
  906. throw new SharingRightsException('no sharing rights on this item');
  907. }
  908. // The current top parent we have access to
  909. $parent = $node;
  910. // initiate real owner.
  911. $owner = $node->getOwner()
  912. ->getUID();
  913. if (!$this->userManager->userExists($owner)) {
  914. return new DataResponse([]);
  915. }
  916. // get node based on the owner, fix owner in case of external storage
  917. $userFolder = $this->rootFolder->getUserFolder($owner);
  918. if ($node->getId() !== $userFolder->getId() && !$userFolder->isSubNode($node)) {
  919. $owner = $node->getOwner()
  920. ->getUID();
  921. $userFolder = $this->rootFolder->getUserFolder($owner);
  922. $node = $userFolder->getFirstNodeById($node->getId());
  923. }
  924. $basePath = $userFolder->getPath();
  925. // generate node list for each parent folders
  926. /** @var Node[] $nodes */
  927. $nodes = [];
  928. while ($node->getPath() !== $basePath) {
  929. $node = $node->getParent();
  930. $nodes[] = $node;
  931. }
  932. // The user that is requesting this list
  933. $currentUserFolder = $this->rootFolder->getUserFolder($this->currentUser);
  934. // for each nodes, retrieve shares.
  935. $shares = [];
  936. foreach ($nodes as $node) {
  937. $getShares = $this->getFormattedShares($owner, $node, false, true);
  938. $currentUserNode = $currentUserFolder->getFirstNodeById($node->getId());
  939. if ($currentUserNode) {
  940. $parent = $currentUserNode;
  941. }
  942. $subPath = $currentUserFolder->getRelativePath($parent->getPath());
  943. foreach ($getShares as &$share) {
  944. $share['via_fileid'] = $parent->getId();
  945. $share['via_path'] = $subPath;
  946. }
  947. $this->mergeFormattedShares($shares, $getShares);
  948. }
  949. return new DataResponse(array_values($shares));
  950. }
  951. /**
  952. * Check whether a set of permissions contains the permissions to check.
  953. */
  954. private function hasPermission(int $permissionsSet, int $permissionsToCheck): bool {
  955. return ($permissionsSet & $permissionsToCheck) === $permissionsToCheck;
  956. }
  957. /**
  958. * @NoAdminRequired
  959. *
  960. * Update a share
  961. *
  962. * @param string $id ID of the share
  963. * @param int|null $permissions New permissions
  964. * @param string|null $password New password
  965. * @param string|null $sendPasswordByTalk New condition if the password should be send over Talk
  966. * @param string|null $publicUpload New condition if public uploading is allowed
  967. * @param string|null $expireDate New expiry date
  968. * @param string|null $note New note
  969. * @param string|null $label New label
  970. * @param string|null $hideDownload New condition if the download should be hidden
  971. * @param string|null $attributes New additional attributes
  972. * @return DataResponse<Http::STATUS_OK, Files_SharingShare, array{}>
  973. * @throws OCSBadRequestException Share could not be updated because the requested changes are invalid
  974. * @throws OCSForbiddenException Missing permissions to update the share
  975. * @throws OCSNotFoundException Share not found
  976. *
  977. * 200: Share updated successfully
  978. */
  979. public function updateShare(
  980. string $id,
  981. ?int $permissions = null,
  982. ?string $password = null,
  983. ?string $sendPasswordByTalk = null,
  984. ?string $publicUpload = null,
  985. ?string $expireDate = null,
  986. ?string $note = null,
  987. ?string $label = null,
  988. ?string $hideDownload = null,
  989. ?string $attributes = null
  990. ): DataResponse {
  991. try {
  992. $share = $this->getShareById($id);
  993. } catch (ShareNotFound $e) {
  994. throw new OCSNotFoundException($this->l->t('Wrong share ID, share does not exist'));
  995. }
  996. $this->lock($share->getNode());
  997. if (!$this->canAccessShare($share, false)) {
  998. throw new OCSNotFoundException($this->l->t('Wrong share ID, share does not exist'));
  999. }
  1000. if (!$this->canEditShare($share)) {
  1001. throw new OCSForbiddenException('You are not allowed to edit incoming shares');
  1002. }
  1003. if (
  1004. $permissions === null &&
  1005. $password === null &&
  1006. $sendPasswordByTalk === null &&
  1007. $publicUpload === null &&
  1008. $expireDate === null &&
  1009. $note === null &&
  1010. $label === null &&
  1011. $hideDownload === null &&
  1012. $attributes === null
  1013. ) {
  1014. throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
  1015. }
  1016. if ($note !== null) {
  1017. $share->setNote($note);
  1018. }
  1019. if ($attributes !== null) {
  1020. $share = $this->setShareAttributes($share, $attributes);
  1021. }
  1022. $this->checkInheritedAttributes($share);
  1023. /**
  1024. * expirationdate, password and publicUpload only make sense for link shares
  1025. */
  1026. if ($share->getShareType() === IShare::TYPE_LINK
  1027. || $share->getShareType() === IShare::TYPE_EMAIL) {
  1028. /**
  1029. * We do not allow editing link shares that the current user
  1030. * doesn't own. This is confusing and lead to errors when
  1031. * someone else edit a password or expiration date without
  1032. * the share owner knowing about it.
  1033. * We only allow deletion
  1034. */
  1035. if ($share->getSharedBy() !== $this->currentUser) {
  1036. throw new OCSForbiddenException('You are not allowed to edit link shares that you don\'t own');
  1037. }
  1038. // Update hide download state
  1039. if ($hideDownload === 'true') {
  1040. $share->setHideDownload(true);
  1041. } elseif ($hideDownload === 'false') {
  1042. $share->setHideDownload(false);
  1043. }
  1044. $newPermissions = null;
  1045. if ($publicUpload === 'true') {
  1046. $newPermissions = Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE;
  1047. } elseif ($publicUpload === 'false') {
  1048. $newPermissions = Constants::PERMISSION_READ;
  1049. }
  1050. if ($permissions !== null) {
  1051. $newPermissions = $permissions;
  1052. $newPermissions = $newPermissions & ~Constants::PERMISSION_SHARE;
  1053. }
  1054. if ($newPermissions !== null) {
  1055. if (!$this->hasPermission($newPermissions, Constants::PERMISSION_READ) && !$this->hasPermission($newPermissions, Constants::PERMISSION_CREATE)) {
  1056. throw new OCSBadRequestException($this->l->t('Share must at least have READ or CREATE permissions'));
  1057. }
  1058. if (!$this->hasPermission($newPermissions, Constants::PERMISSION_READ) && (
  1059. $this->hasPermission($newPermissions, Constants::PERMISSION_UPDATE) || $this->hasPermission($newPermissions, Constants::PERMISSION_DELETE)
  1060. )) {
  1061. throw new OCSBadRequestException($this->l->t('Share must have READ permission if UPDATE or DELETE permission is set'));
  1062. }
  1063. }
  1064. if (
  1065. // legacy
  1066. $newPermissions === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE) ||
  1067. // correct
  1068. $newPermissions === (Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE)
  1069. ) {
  1070. if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
  1071. throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
  1072. }
  1073. if (!($share->getNode() instanceof \OCP\Files\Folder)) {
  1074. throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
  1075. }
  1076. // normalize to correct public upload permissions
  1077. if ($publicUpload === 'true') {
  1078. $newPermissions = Constants::PERMISSION_READ | Constants::PERMISSION_CREATE | Constants::PERMISSION_UPDATE | Constants::PERMISSION_DELETE;
  1079. }
  1080. }
  1081. if ($newPermissions !== null) {
  1082. // TODO: It might make sense to have a dedicated setting to allow/deny converting link shares into federated ones
  1083. if (($newPermissions & Constants::PERMISSION_READ) && $this->shareManager->outgoingServer2ServerSharesAllowed()) {
  1084. $newPermissions |= Constants::PERMISSION_SHARE;
  1085. }
  1086. $share->setPermissions($newPermissions);
  1087. $permissions = $newPermissions;
  1088. }
  1089. if ($password === '') {
  1090. $share->setPassword(null);
  1091. } elseif ($password !== null) {
  1092. $share->setPassword($password);
  1093. }
  1094. if ($label !== null) {
  1095. if (strlen($label) > 255) {
  1096. throw new OCSBadRequestException("Maximum label length is 255");
  1097. }
  1098. $share->setLabel($label);
  1099. }
  1100. if ($sendPasswordByTalk === 'true') {
  1101. if (!$this->appManager->isEnabledForUser('spreed')) {
  1102. throw new OCSForbiddenException($this->l->t('"Sending the password by Nextcloud Talk" for sharing a file or folder failed because Nextcloud Talk is not enabled.'));
  1103. }
  1104. $share->setSendPasswordByTalk(true);
  1105. } elseif ($sendPasswordByTalk !== null) {
  1106. $share->setSendPasswordByTalk(false);
  1107. }
  1108. }
  1109. // NOT A LINK SHARE
  1110. else {
  1111. if ($permissions !== null) {
  1112. $share->setPermissions($permissions);
  1113. }
  1114. }
  1115. if ($expireDate === '') {
  1116. $share->setExpirationDate(null);
  1117. } elseif ($expireDate !== null) {
  1118. try {
  1119. $expireDate = $this->parseDate($expireDate);
  1120. } catch (\Exception $e) {
  1121. throw new OCSBadRequestException($e->getMessage(), $e);
  1122. }
  1123. $share->setExpirationDate($expireDate);
  1124. }
  1125. try {
  1126. $share = $this->shareManager->updateShare($share);
  1127. } catch (GenericShareException $e) {
  1128. $code = $e->getCode() === 0 ? 403 : $e->getCode();
  1129. throw new OCSException($e->getHint(), (int)$code);
  1130. } catch (\Exception $e) {
  1131. throw new OCSBadRequestException($e->getMessage(), $e);
  1132. }
  1133. return new DataResponse($this->formatShare($share));
  1134. }
  1135. /**
  1136. * @NoAdminRequired
  1137. *
  1138. * Get all shares that are still pending
  1139. *
  1140. * @return DataResponse<Http::STATUS_OK, Files_SharingShare[], array{}>
  1141. *
  1142. * 200: Pending shares returned
  1143. */
  1144. public function pendingShares(): DataResponse {
  1145. $pendingShares = [];
  1146. $shareTypes = [
  1147. IShare::TYPE_USER,
  1148. IShare::TYPE_GROUP
  1149. ];
  1150. foreach ($shareTypes as $shareType) {
  1151. $shares = $this->shareManager->getSharedWith($this->currentUser, $shareType, null, -1, 0);
  1152. foreach ($shares as $share) {
  1153. if ($share->getStatus() === IShare::STATUS_PENDING || $share->getStatus() === IShare::STATUS_REJECTED) {
  1154. $pendingShares[] = $share;
  1155. }
  1156. }
  1157. }
  1158. $result = array_filter(array_map(function (IShare $share) {
  1159. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  1160. $node = $userFolder->getFirstNodeById($share->getNodeId());
  1161. if (!$node) {
  1162. // fallback to guessing the path
  1163. $node = $userFolder->get($share->getTarget());
  1164. if ($node === null || $share->getTarget() === '') {
  1165. return null;
  1166. }
  1167. }
  1168. try {
  1169. $formattedShare = $this->formatShare($share, $node);
  1170. $formattedShare['path'] = '/' . $share->getNode()->getName();
  1171. $formattedShare['permissions'] = 0;
  1172. return $formattedShare;
  1173. } catch (NotFoundException $e) {
  1174. return null;
  1175. }
  1176. }, $pendingShares), function ($entry) {
  1177. return $entry !== null;
  1178. });
  1179. return new DataResponse($result);
  1180. }
  1181. /**
  1182. * @NoAdminRequired
  1183. *
  1184. * Accept a share
  1185. *
  1186. * @param string $id ID of the share
  1187. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  1188. * @throws OCSNotFoundException Share not found
  1189. * @throws OCSException
  1190. * @throws OCSBadRequestException Share could not be accepted
  1191. *
  1192. * 200: Share accepted successfully
  1193. */
  1194. public function acceptShare(string $id): DataResponse {
  1195. try {
  1196. $share = $this->getShareById($id);
  1197. } catch (ShareNotFound $e) {
  1198. throw new OCSNotFoundException($this->l->t('Wrong share ID, share does not exist'));
  1199. }
  1200. if (!$this->canAccessShare($share)) {
  1201. throw new OCSNotFoundException($this->l->t('Wrong share ID, share does not exist'));
  1202. }
  1203. try {
  1204. $this->shareManager->acceptShare($share, $this->currentUser);
  1205. } catch (GenericShareException $e) {
  1206. $code = $e->getCode() === 0 ? 403 : $e->getCode();
  1207. throw new OCSException($e->getHint(), (int)$code);
  1208. } catch (\Exception $e) {
  1209. throw new OCSBadRequestException($e->getMessage(), $e);
  1210. }
  1211. return new DataResponse();
  1212. }
  1213. /**
  1214. * Does the user have read permission on the share
  1215. *
  1216. * @param \OCP\Share\IShare $share the share to check
  1217. * @param boolean $checkGroups check groups as well?
  1218. * @return boolean
  1219. * @throws NotFoundException
  1220. *
  1221. * @suppress PhanUndeclaredClassMethod
  1222. */
  1223. protected function canAccessShare(\OCP\Share\IShare $share, bool $checkGroups = true): bool {
  1224. // A file with permissions 0 can't be accessed by us. So Don't show it
  1225. if ($share->getPermissions() === 0) {
  1226. return false;
  1227. }
  1228. // Owner of the file and the sharer of the file can always get share
  1229. if ($share->getShareOwner() === $this->currentUser
  1230. || $share->getSharedBy() === $this->currentUser) {
  1231. return true;
  1232. }
  1233. // If the share is shared with you, you can access it!
  1234. if ($share->getShareType() === IShare::TYPE_USER
  1235. && $share->getSharedWith() === $this->currentUser) {
  1236. return true;
  1237. }
  1238. // Have reshare rights on the shared file/folder ?
  1239. // Does the currentUser have access to the shared file?
  1240. $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
  1241. $file = $userFolder->getFirstNodeById($share->getNodeId());
  1242. if ($file && $this->shareProviderResharingRights($this->currentUser, $share, $file)) {
  1243. return true;
  1244. }
  1245. // If in the recipient group, you can see the share
  1246. if ($checkGroups && $share->getShareType() === IShare::TYPE_GROUP) {
  1247. $sharedWith = $this->groupManager->get($share->getSharedWith());
  1248. $user = $this->userManager->get($this->currentUser);
  1249. if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
  1250. return true;
  1251. }
  1252. }
  1253. if ($share->getShareType() === IShare::TYPE_CIRCLE) {
  1254. // TODO: have a sanity check like above?
  1255. return true;
  1256. }
  1257. if ($share->getShareType() === IShare::TYPE_ROOM) {
  1258. try {
  1259. return $this->getRoomShareHelper()->canAccessShare($share, $this->currentUser);
  1260. } catch (QueryException $e) {
  1261. return false;
  1262. }
  1263. }
  1264. if ($share->getShareType() === IShare::TYPE_DECK) {
  1265. try {
  1266. return $this->getDeckShareHelper()->canAccessShare($share, $this->currentUser);
  1267. } catch (QueryException $e) {
  1268. return false;
  1269. }
  1270. }
  1271. if ($share->getShareType() === IShare::TYPE_SCIENCEMESH) {
  1272. try {
  1273. return $this->getSciencemeshShareHelper()->canAccessShare($share, $this->currentUser);
  1274. } catch (QueryException $e) {
  1275. return false;
  1276. }
  1277. }
  1278. return false;
  1279. }
  1280. /**
  1281. * Does the user have edit permission on the share
  1282. *
  1283. * @param \OCP\Share\IShare $share the share to check
  1284. * @return boolean
  1285. */
  1286. protected function canEditShare(\OCP\Share\IShare $share): bool {
  1287. // A file with permissions 0 can't be accessed by us. So Don't show it
  1288. if ($share->getPermissions() === 0) {
  1289. return false;
  1290. }
  1291. // The owner of the file and the creator of the share
  1292. // can always edit the share
  1293. if ($share->getShareOwner() === $this->currentUser ||
  1294. $share->getSharedBy() === $this->currentUser
  1295. ) {
  1296. return true;
  1297. }
  1298. //! we do NOT support some kind of `admin` in groups.
  1299. //! You cannot edit shares shared to a group you're
  1300. //! a member of if you're not the share owner or the file owner!
  1301. return false;
  1302. }
  1303. /**
  1304. * Does the user have delete permission on the share
  1305. *
  1306. * @param \OCP\Share\IShare $share the share to check
  1307. * @return boolean
  1308. */
  1309. protected function canDeleteShare(\OCP\Share\IShare $share): bool {
  1310. // A file with permissions 0 can't be accessed by us. So Don't show it
  1311. if ($share->getPermissions() === 0) {
  1312. return false;
  1313. }
  1314. // if the user is the recipient, i can unshare
  1315. // the share with self
  1316. if ($share->getShareType() === IShare::TYPE_USER &&
  1317. $share->getSharedWith() === $this->currentUser
  1318. ) {
  1319. return true;
  1320. }
  1321. // The owner of the file and the creator of the share
  1322. // can always delete the share
  1323. if ($share->getShareOwner() === $this->currentUser ||
  1324. $share->getSharedBy() === $this->currentUser
  1325. ) {
  1326. return true;
  1327. }
  1328. return false;
  1329. }
  1330. /**
  1331. * Does the user have delete permission on the share
  1332. * This differs from the canDeleteShare function as it only
  1333. * remove the share for the current user. It does NOT
  1334. * completely delete the share but only the mount point.
  1335. * It can then be restored from the deleted shares section.
  1336. *
  1337. * @param \OCP\Share\IShare $share the share to check
  1338. * @return boolean
  1339. *
  1340. * @suppress PhanUndeclaredClassMethod
  1341. */
  1342. protected function canDeleteShareFromSelf(\OCP\Share\IShare $share): bool {
  1343. if ($share->getShareType() !== IShare::TYPE_GROUP &&
  1344. $share->getShareType() !== IShare::TYPE_ROOM &&
  1345. $share->getShareType() !== IShare::TYPE_DECK &&
  1346. $share->getShareType() !== IShare::TYPE_SCIENCEMESH
  1347. ) {
  1348. return false;
  1349. }
  1350. if ($share->getShareOwner() === $this->currentUser ||
  1351. $share->getSharedBy() === $this->currentUser
  1352. ) {
  1353. // Delete the whole share, not just for self
  1354. return false;
  1355. }
  1356. // If in the recipient group, you can delete the share from self
  1357. if ($share->getShareType() === IShare::TYPE_GROUP) {
  1358. $sharedWith = $this->groupManager->get($share->getSharedWith());
  1359. $user = $this->userManager->get($this->currentUser);
  1360. if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
  1361. return true;
  1362. }
  1363. }
  1364. if ($share->getShareType() === IShare::TYPE_ROOM) {
  1365. try {
  1366. return $this->getRoomShareHelper()->canAccessShare($share, $this->currentUser);
  1367. } catch (QueryException $e) {
  1368. return false;
  1369. }
  1370. }
  1371. if ($share->getShareType() === IShare::TYPE_DECK) {
  1372. try {
  1373. return $this->getDeckShareHelper()->canAccessShare($share, $this->currentUser);
  1374. } catch (QueryException $e) {
  1375. return false;
  1376. }
  1377. }
  1378. if ($share->getShareType() === IShare::TYPE_SCIENCEMESH) {
  1379. try {
  1380. return $this->getSciencemeshShareHelper()->canAccessShare($share, $this->currentUser);
  1381. } catch (QueryException $e) {
  1382. return false;
  1383. }
  1384. }
  1385. return false;
  1386. }
  1387. /**
  1388. * Make sure that the passed date is valid ISO 8601
  1389. * So YYYY-MM-DD
  1390. * If not throw an exception
  1391. *
  1392. * @param string $expireDate
  1393. *
  1394. * @throws \Exception
  1395. * @return \DateTime
  1396. */
  1397. private function parseDate(string $expireDate): \DateTime {
  1398. try {
  1399. $date = new \DateTime(trim($expireDate, "\""), $this->dateTimeZone->getTimeZone());
  1400. // Make sure it expires at midnight in owner timezone
  1401. $date->setTime(0, 0, 0);
  1402. } catch (\Exception $e) {
  1403. throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
  1404. }
  1405. // Use server timezone to store the date
  1406. $date->setTimezone(new \DateTimeZone(date_default_timezone_get()));
  1407. return $date;
  1408. }
  1409. /**
  1410. * Since we have multiple providers but the OCS Share API v1 does
  1411. * not support this we need to check all backends.
  1412. *
  1413. * @param string $id
  1414. * @return \OCP\Share\IShare
  1415. * @throws ShareNotFound
  1416. */
  1417. private function getShareById(string $id): IShare {
  1418. $share = null;
  1419. // First check if it is an internal share.
  1420. try {
  1421. $share = $this->shareManager->getShareById('ocinternal:' . $id, $this->currentUser);
  1422. return $share;
  1423. } catch (ShareNotFound $e) {
  1424. // Do nothing, just try the other share type
  1425. }
  1426. try {
  1427. if ($this->shareManager->shareProviderExists(IShare::TYPE_CIRCLE)) {
  1428. $share = $this->shareManager->getShareById('ocCircleShare:' . $id, $this->currentUser);
  1429. return $share;
  1430. }
  1431. } catch (ShareNotFound $e) {
  1432. // Do nothing, just try the other share type
  1433. }
  1434. try {
  1435. if ($this->shareManager->shareProviderExists(IShare::TYPE_EMAIL)) {
  1436. $share = $this->shareManager->getShareById('ocMailShare:' . $id, $this->currentUser);
  1437. return $share;
  1438. }
  1439. } catch (ShareNotFound $e) {
  1440. // Do nothing, just try the other share type
  1441. }
  1442. try {
  1443. $share = $this->shareManager->getShareById('ocRoomShare:' . $id, $this->currentUser);
  1444. return $share;
  1445. } catch (ShareNotFound $e) {
  1446. // Do nothing, just try the other share type
  1447. }
  1448. try {
  1449. if ($this->shareManager->shareProviderExists(IShare::TYPE_DECK)) {
  1450. $share = $this->shareManager->getShareById('deck:' . $id, $this->currentUser);
  1451. return $share;
  1452. }
  1453. } catch (ShareNotFound $e) {
  1454. // Do nothing, just try the other share type
  1455. }
  1456. try {
  1457. if ($this->shareManager->shareProviderExists(IShare::TYPE_SCIENCEMESH)) {
  1458. $share = $this->shareManager->getShareById('sciencemesh:' . $id, $this->currentUser);
  1459. return $share;
  1460. }
  1461. } catch (ShareNotFound $e) {
  1462. // Do nothing, just try the other share type
  1463. }
  1464. if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
  1465. throw new ShareNotFound();
  1466. }
  1467. $share = $this->shareManager->getShareById('ocFederatedSharing:' . $id, $this->currentUser);
  1468. return $share;
  1469. }
  1470. /**
  1471. * Lock a Node
  1472. *
  1473. * @param \OCP\Files\Node $node
  1474. * @throws LockedException
  1475. */
  1476. private function lock(\OCP\Files\Node $node) {
  1477. $node->lock(ILockingProvider::LOCK_SHARED);
  1478. $this->lockedNode = $node;
  1479. }
  1480. /**
  1481. * Cleanup the remaining locks
  1482. * @throws LockedException
  1483. */
  1484. public function cleanup() {
  1485. if ($this->lockedNode !== null) {
  1486. $this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
  1487. }
  1488. }
  1489. /**
  1490. * Returns the helper of ShareAPIController for room shares.
  1491. *
  1492. * If the Talk application is not enabled or the helper is not available
  1493. * a QueryException is thrown instead.
  1494. *
  1495. * @return \OCA\Talk\Share\Helper\ShareAPIController
  1496. * @throws QueryException
  1497. */
  1498. private function getRoomShareHelper() {
  1499. if (!$this->appManager->isEnabledForUser('spreed')) {
  1500. throw new QueryException();
  1501. }
  1502. return $this->serverContainer->get('\OCA\Talk\Share\Helper\ShareAPIController');
  1503. }
  1504. /**
  1505. * Returns the helper of ShareAPIHelper for deck shares.
  1506. *
  1507. * If the Deck application is not enabled or the helper is not available
  1508. * a QueryException is thrown instead.
  1509. *
  1510. * @return \OCA\Deck\Sharing\ShareAPIHelper
  1511. * @throws QueryException
  1512. */
  1513. private function getDeckShareHelper() {
  1514. if (!$this->appManager->isEnabledForUser('deck')) {
  1515. throw new QueryException();
  1516. }
  1517. return $this->serverContainer->get('\OCA\Deck\Sharing\ShareAPIHelper');
  1518. }
  1519. /**
  1520. * Returns the helper of ShareAPIHelper for sciencemesh shares.
  1521. *
  1522. * If the sciencemesh application is not enabled or the helper is not available
  1523. * a QueryException is thrown instead.
  1524. *
  1525. * @return \OCA\Deck\Sharing\ShareAPIHelper
  1526. * @throws QueryException
  1527. */
  1528. private function getSciencemeshShareHelper() {
  1529. if (!$this->appManager->isEnabledForUser('sciencemesh')) {
  1530. throw new QueryException();
  1531. }
  1532. return $this->serverContainer->get('\OCA\ScienceMesh\Sharing\ShareAPIHelper');
  1533. }
  1534. /**
  1535. * @param string $viewer
  1536. * @param Node $node
  1537. * @param bool $reShares
  1538. *
  1539. * @return IShare[]
  1540. */
  1541. private function getSharesFromNode(string $viewer, $node, bool $reShares): array {
  1542. $providers = [
  1543. IShare::TYPE_USER,
  1544. IShare::TYPE_GROUP,
  1545. IShare::TYPE_LINK,
  1546. IShare::TYPE_EMAIL,
  1547. IShare::TYPE_CIRCLE,
  1548. IShare::TYPE_ROOM,
  1549. IShare::TYPE_DECK,
  1550. IShare::TYPE_SCIENCEMESH
  1551. ];
  1552. // Should we assume that the (currentUser) viewer is the owner of the node !?
  1553. $shares = [];
  1554. foreach ($providers as $provider) {
  1555. if (!$this->shareManager->shareProviderExists($provider)) {
  1556. continue;
  1557. }
  1558. $providerShares =
  1559. $this->shareManager->getSharesBy($viewer, $provider, $node, $reShares, -1, 0);
  1560. $shares = array_merge($shares, $providerShares);
  1561. }
  1562. if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
  1563. $federatedShares = $this->shareManager->getSharesBy(
  1564. $this->currentUser, IShare::TYPE_REMOTE, $node, $reShares, -1, 0
  1565. );
  1566. $shares = array_merge($shares, $federatedShares);
  1567. }
  1568. if ($this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
  1569. $federatedShares = $this->shareManager->getSharesBy(
  1570. $this->currentUser, IShare::TYPE_REMOTE_GROUP, $node, $reShares, -1, 0
  1571. );
  1572. $shares = array_merge($shares, $federatedShares);
  1573. }
  1574. return $shares;
  1575. }
  1576. /**
  1577. * @param Node $node
  1578. *
  1579. * @throws SharingRightsException
  1580. */
  1581. private function confirmSharingRights(Node $node): void {
  1582. if (!$this->hasResharingRights($this->currentUser, $node)) {
  1583. throw new SharingRightsException('no sharing rights on this item');
  1584. }
  1585. }
  1586. /**
  1587. * @param string $viewer
  1588. * @param Node $node
  1589. *
  1590. * @return bool
  1591. */
  1592. private function hasResharingRights($viewer, $node): bool {
  1593. if ($viewer === $node->getOwner()->getUID()) {
  1594. return true;
  1595. }
  1596. foreach ([$node, $node->getParent()] as $node) {
  1597. $shares = $this->getSharesFromNode($viewer, $node, true);
  1598. foreach ($shares as $share) {
  1599. try {
  1600. if ($this->shareProviderResharingRights($viewer, $share, $node)) {
  1601. return true;
  1602. }
  1603. } catch (InvalidPathException | NotFoundException $e) {
  1604. }
  1605. }
  1606. }
  1607. return false;
  1608. }
  1609. /**
  1610. * Returns if we can find resharing rights in an IShare object for a specific user.
  1611. *
  1612. * @suppress PhanUndeclaredClassMethod
  1613. *
  1614. * @param string $userId
  1615. * @param IShare $share
  1616. * @param Node $node
  1617. *
  1618. * @return bool
  1619. * @throws NotFoundException
  1620. * @throws InvalidPathException
  1621. */
  1622. private function shareProviderResharingRights(string $userId, IShare $share, $node): bool {
  1623. if ($share->getShareOwner() === $userId) {
  1624. return true;
  1625. }
  1626. // we check that current user have parent resharing rights on the current file
  1627. if ($node !== null && ($node->getPermissions() & Constants::PERMISSION_SHARE) !== 0) {
  1628. return true;
  1629. }
  1630. if ((\OCP\Constants::PERMISSION_SHARE & $share->getPermissions()) === 0) {
  1631. return false;
  1632. }
  1633. if ($share->getShareType() === IShare::TYPE_USER && $share->getSharedWith() === $userId) {
  1634. return true;
  1635. }
  1636. if ($share->getShareType() === IShare::TYPE_GROUP && $this->groupManager->isInGroup($userId, $share->getSharedWith())) {
  1637. return true;
  1638. }
  1639. if ($share->getShareType() === IShare::TYPE_CIRCLE && \OC::$server->getAppManager()->isEnabledForUser('circles')
  1640. && class_exists('\OCA\Circles\Api\v1\Circles')) {
  1641. $hasCircleId = (str_ends_with($share->getSharedWith(), ']'));
  1642. $shareWithStart = ($hasCircleId ? strrpos($share->getSharedWith(), '[') + 1 : 0);
  1643. $shareWithLength = ($hasCircleId ? -1 : strpos($share->getSharedWith(), ' '));
  1644. if ($shareWithLength === false) {
  1645. $sharedWith = substr($share->getSharedWith(), $shareWithStart);
  1646. } else {
  1647. $sharedWith = substr($share->getSharedWith(), $shareWithStart, $shareWithLength);
  1648. }
  1649. try {
  1650. $member = \OCA\Circles\Api\v1\Circles::getMember($sharedWith, $userId, 1);
  1651. if ($member->getLevel() >= 4) {
  1652. return true;
  1653. }
  1654. return false;
  1655. } catch (QueryException $e) {
  1656. return false;
  1657. }
  1658. }
  1659. return false;
  1660. }
  1661. /**
  1662. * Get all the shares for the current user
  1663. *
  1664. * @param Node|null $path
  1665. * @param boolean $reshares
  1666. * @return IShare[]
  1667. */
  1668. private function getAllShares(?Node $path = null, bool $reshares = false) {
  1669. // Get all shares
  1670. $userShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_USER, $path, $reshares, -1, 0);
  1671. $groupShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_GROUP, $path, $reshares, -1, 0);
  1672. $linkShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_LINK, $path, $reshares, -1, 0);
  1673. // EMAIL SHARES
  1674. $mailShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_EMAIL, $path, $reshares, -1, 0);
  1675. // CIRCLE SHARES
  1676. $circleShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_CIRCLE, $path, $reshares, -1, 0);
  1677. // TALK SHARES
  1678. $roomShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_ROOM, $path, $reshares, -1, 0);
  1679. // DECK SHARES
  1680. $deckShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_DECK, $path, $reshares, -1, 0);
  1681. // SCIENCEMESH SHARES
  1682. $sciencemeshShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_SCIENCEMESH, $path, $reshares, -1, 0);
  1683. // FEDERATION
  1684. if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
  1685. $federatedShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_REMOTE, $path, $reshares, -1, 0);
  1686. } else {
  1687. $federatedShares = [];
  1688. }
  1689. if ($this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
  1690. $federatedGroupShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_REMOTE_GROUP, $path, $reshares, -1, 0);
  1691. } else {
  1692. $federatedGroupShares = [];
  1693. }
  1694. return array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares, $roomShares, $deckShares, $sciencemeshShares, $federatedShares, $federatedGroupShares);
  1695. }
  1696. /**
  1697. * merging already formatted shares.
  1698. * We'll make an associative array to easily detect duplicate Ids.
  1699. * Keys _needs_ to be removed after all shares are retrieved and merged.
  1700. *
  1701. * @param array $shares
  1702. * @param array $newShares
  1703. */
  1704. private function mergeFormattedShares(array &$shares, array $newShares) {
  1705. foreach ($newShares as $newShare) {
  1706. if (!array_key_exists($newShare['id'], $shares)) {
  1707. $shares[$newShare['id']] = $newShare;
  1708. }
  1709. }
  1710. }
  1711. /**
  1712. * @param IShare $share
  1713. * @param string|null $attributesString
  1714. * @return IShare modified share
  1715. */
  1716. private function setShareAttributes(IShare $share, ?string $attributesString) {
  1717. $newShareAttributes = null;
  1718. if ($attributesString !== null) {
  1719. $newShareAttributes = $this->shareManager->newShare()->newAttributes();
  1720. $formattedShareAttributes = \json_decode($attributesString, true);
  1721. if (is_array($formattedShareAttributes)) {
  1722. foreach ($formattedShareAttributes as $formattedAttr) {
  1723. $newShareAttributes->setAttribute(
  1724. $formattedAttr['scope'],
  1725. $formattedAttr['key'],
  1726. is_string($formattedAttr['enabled']) ? (bool) \json_decode($formattedAttr['enabled']) : $formattedAttr['enabled']
  1727. );
  1728. }
  1729. } else {
  1730. throw new OCSBadRequestException('Invalid share attributes provided: \"' . $attributesString . '\"');
  1731. }
  1732. }
  1733. $share->setAttributes($newShareAttributes);
  1734. return $share;
  1735. }
  1736. private function checkInheritedAttributes(IShare $share): void {
  1737. if (!$share->getSharedBy()) {
  1738. return; // Probably in a test
  1739. }
  1740. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  1741. $node = $userFolder->getFirstNodeById($share->getNodeId());
  1742. if (!$node) {
  1743. return;
  1744. }
  1745. if ($node->getStorage()->instanceOfStorage(SharedStorage::class)) {
  1746. $storage = $node->getStorage();
  1747. if ($storage instanceof Wrapper) {
  1748. $storage = $storage->getInstanceOfStorage(SharedStorage::class);
  1749. if ($storage === null) {
  1750. throw new \RuntimeException('Should not happen, instanceOfStorage but getInstanceOfStorage return null');
  1751. }
  1752. } else {
  1753. throw new \RuntimeException('Should not happen, instanceOfStorage but not a wrapper');
  1754. }
  1755. /** @var \OCA\Files_Sharing\SharedStorage $storage */
  1756. $inheritedAttributes = $storage->getShare()->getAttributes();
  1757. if ($inheritedAttributes !== null && $inheritedAttributes->getAttribute('permissions', 'download') === false) {
  1758. $share->setHideDownload(true);
  1759. $attributes = $share->getAttributes();
  1760. if ($attributes) {
  1761. $attributes->setAttribute('permissions', 'download', false);
  1762. $share->setAttributes($attributes);
  1763. }
  1764. }
  1765. }
  1766. }
  1767. }