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 67KB

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