ShareAPIController.php 67 KB

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