ShareAPIController.php 69 KB

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