ShareAPIController.php 69 KB

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