ShareAPIController.php 67 KB

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