You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ShareAPIController.php 59KB

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