Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

ShareAPIController.php 65KB

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