ShareAPIController.php 69 KB

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