ShareAPIController.php 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127
  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 FilesSharingShare 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 FilesSharingShare
  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, FilesSharingShare, 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, FilesSharingShare, 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 FilesSharingShare[]
  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 FilesSharingShare[]
  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, FilesSharingShare[], 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 FilesSharingShare[]
  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, FilesSharingShare[], 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, FilesSharingShare, 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, FilesSharingShare[], array{}>
  1234. */
  1235. public function pendingShares(): DataResponse {
  1236. $pendingShares = [];
  1237. $shareTypes = [
  1238. IShare::TYPE_USER,
  1239. IShare::TYPE_GROUP
  1240. ];
  1241. foreach ($shareTypes as $shareType) {
  1242. $shares = $this->shareManager->getSharedWith($this->currentUser, $shareType, null, -1, 0);
  1243. foreach ($shares as $share) {
  1244. if ($share->getStatus() === IShare::STATUS_PENDING || $share->getStatus() === IShare::STATUS_REJECTED) {
  1245. $pendingShares[] = $share;
  1246. }
  1247. }
  1248. }
  1249. $result = array_filter(array_map(function (IShare $share) {
  1250. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  1251. $nodes = $userFolder->getById($share->getNodeId());
  1252. if (empty($nodes)) {
  1253. // fallback to guessing the path
  1254. $node = $userFolder->get($share->getTarget());
  1255. if ($node === null || $share->getTarget() === '') {
  1256. return null;
  1257. }
  1258. } else {
  1259. $node = $nodes[0];
  1260. }
  1261. try {
  1262. $formattedShare = $this->formatShare($share, $node);
  1263. $formattedShare['path'] = '/' . $share->getNode()->getName();
  1264. $formattedShare['permissions'] = 0;
  1265. return $formattedShare;
  1266. } catch (NotFoundException $e) {
  1267. return null;
  1268. }
  1269. }, $pendingShares), function ($entry) {
  1270. return $entry !== null;
  1271. });
  1272. return new DataResponse($result);
  1273. }
  1274. /**
  1275. * @NoAdminRequired
  1276. *
  1277. * Accept a share
  1278. *
  1279. * @param string $id ID of the share
  1280. * @return DataResponse<Http::STATUS_OK, array<empty>, array{}>
  1281. * @throws OCSNotFoundException Share not found
  1282. * @throws OCSException
  1283. * @throws OCSBadRequestException Share could not be accepted
  1284. *
  1285. * 200: Share accepted successfully
  1286. */
  1287. public function acceptShare(string $id): DataResponse {
  1288. try {
  1289. $share = $this->getShareById($id);
  1290. } catch (ShareNotFound $e) {
  1291. throw new OCSNotFoundException($this->l->t('Wrong share ID, share does not exist'));
  1292. }
  1293. if (!$this->canAccessShare($share)) {
  1294. throw new OCSNotFoundException($this->l->t('Wrong share ID, share does not exist'));
  1295. }
  1296. try {
  1297. $this->shareManager->acceptShare($share, $this->currentUser);
  1298. } catch (GenericShareException $e) {
  1299. $code = $e->getCode() === 0 ? 403 : $e->getCode();
  1300. throw new OCSException($e->getHint(), (int)$code);
  1301. } catch (\Exception $e) {
  1302. throw new OCSBadRequestException($e->getMessage(), $e);
  1303. }
  1304. return new DataResponse();
  1305. }
  1306. /**
  1307. * Does the user have read permission on the share
  1308. *
  1309. * @param \OCP\Share\IShare $share the share to check
  1310. * @param boolean $checkGroups check groups as well?
  1311. * @return boolean
  1312. * @throws NotFoundException
  1313. *
  1314. * @suppress PhanUndeclaredClassMethod
  1315. */
  1316. protected function canAccessShare(\OCP\Share\IShare $share, bool $checkGroups = true): bool {
  1317. // A file with permissions 0 can't be accessed by us. So Don't show it
  1318. if ($share->getPermissions() === 0) {
  1319. return false;
  1320. }
  1321. // Owner of the file and the sharer of the file can always get share
  1322. if ($share->getShareOwner() === $this->currentUser
  1323. || $share->getSharedBy() === $this->currentUser) {
  1324. return true;
  1325. }
  1326. // If the share is shared with you, you can access it!
  1327. if ($share->getShareType() === IShare::TYPE_USER
  1328. && $share->getSharedWith() === $this->currentUser) {
  1329. return true;
  1330. }
  1331. // Have reshare rights on the shared file/folder ?
  1332. // Does the currentUser have access to the shared file?
  1333. $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
  1334. $files = $userFolder->getById($share->getNodeId());
  1335. if (!empty($files) && $this->shareProviderResharingRights($this->currentUser, $share, $files[0])) {
  1336. return true;
  1337. }
  1338. // If in the recipient group, you can see the share
  1339. if ($checkGroups && $share->getShareType() === IShare::TYPE_GROUP) {
  1340. $sharedWith = $this->groupManager->get($share->getSharedWith());
  1341. $user = $this->userManager->get($this->currentUser);
  1342. if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
  1343. return true;
  1344. }
  1345. }
  1346. if ($share->getShareType() === IShare::TYPE_CIRCLE) {
  1347. // TODO: have a sanity check like above?
  1348. return true;
  1349. }
  1350. if ($share->getShareType() === IShare::TYPE_ROOM) {
  1351. try {
  1352. return $this->getRoomShareHelper()->canAccessShare($share, $this->currentUser);
  1353. } catch (QueryException $e) {
  1354. return false;
  1355. }
  1356. }
  1357. if ($share->getShareType() === IShare::TYPE_DECK) {
  1358. try {
  1359. return $this->getDeckShareHelper()->canAccessShare($share, $this->currentUser);
  1360. } catch (QueryException $e) {
  1361. return false;
  1362. }
  1363. }
  1364. if ($share->getShareType() === IShare::TYPE_SCIENCEMESH) {
  1365. try {
  1366. return $this->getSciencemeshShareHelper()->canAccessShare($share, $this->currentUser);
  1367. } catch (QueryException $e) {
  1368. return false;
  1369. }
  1370. }
  1371. return false;
  1372. }
  1373. /**
  1374. * Does the user have edit permission on the share
  1375. *
  1376. * @param \OCP\Share\IShare $share the share to check
  1377. * @return boolean
  1378. */
  1379. protected function canEditShare(\OCP\Share\IShare $share): bool {
  1380. // A file with permissions 0 can't be accessed by us. So Don't show it
  1381. if ($share->getPermissions() === 0) {
  1382. return false;
  1383. }
  1384. // The owner of the file and the creator of the share
  1385. // can always edit the share
  1386. if ($share->getShareOwner() === $this->currentUser ||
  1387. $share->getSharedBy() === $this->currentUser
  1388. ) {
  1389. return true;
  1390. }
  1391. //! we do NOT support some kind of `admin` in groups.
  1392. //! You cannot edit shares shared to a group you're
  1393. //! a member of if you're not the share owner or the file owner!
  1394. return false;
  1395. }
  1396. /**
  1397. * Does the user have delete permission on the share
  1398. *
  1399. * @param \OCP\Share\IShare $share the share to check
  1400. * @return boolean
  1401. */
  1402. protected function canDeleteShare(\OCP\Share\IShare $share): bool {
  1403. // A file with permissions 0 can't be accessed by us. So Don't show it
  1404. if ($share->getPermissions() === 0) {
  1405. return false;
  1406. }
  1407. // if the user is the recipient, i can unshare
  1408. // the share with self
  1409. if ($share->getShareType() === IShare::TYPE_USER &&
  1410. $share->getSharedWith() === $this->currentUser
  1411. ) {
  1412. return true;
  1413. }
  1414. // The owner of the file and the creator of the share
  1415. // can always delete the share
  1416. if ($share->getShareOwner() === $this->currentUser ||
  1417. $share->getSharedBy() === $this->currentUser
  1418. ) {
  1419. return true;
  1420. }
  1421. return false;
  1422. }
  1423. /**
  1424. * Does the user have delete permission on the share
  1425. * This differs from the canDeleteShare function as it only
  1426. * remove the share for the current user. It does NOT
  1427. * completely delete the share but only the mount point.
  1428. * It can then be restored from the deleted shares section.
  1429. *
  1430. * @param \OCP\Share\IShare $share the share to check
  1431. * @return boolean
  1432. *
  1433. * @suppress PhanUndeclaredClassMethod
  1434. */
  1435. protected function canDeleteShareFromSelf(\OCP\Share\IShare $share): bool {
  1436. if ($share->getShareType() !== IShare::TYPE_GROUP &&
  1437. $share->getShareType() !== IShare::TYPE_ROOM &&
  1438. $share->getShareType() !== IShare::TYPE_DECK &&
  1439. $share->getShareType() !== IShare::TYPE_SCIENCEMESH
  1440. ) {
  1441. return false;
  1442. }
  1443. if ($share->getShareOwner() === $this->currentUser ||
  1444. $share->getSharedBy() === $this->currentUser
  1445. ) {
  1446. // Delete the whole share, not just for self
  1447. return false;
  1448. }
  1449. // If in the recipient group, you can delete the share from self
  1450. if ($share->getShareType() === IShare::TYPE_GROUP) {
  1451. $sharedWith = $this->groupManager->get($share->getSharedWith());
  1452. $user = $this->userManager->get($this->currentUser);
  1453. if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
  1454. return true;
  1455. }
  1456. }
  1457. if ($share->getShareType() === IShare::TYPE_ROOM) {
  1458. try {
  1459. return $this->getRoomShareHelper()->canAccessShare($share, $this->currentUser);
  1460. } catch (QueryException $e) {
  1461. return false;
  1462. }
  1463. }
  1464. if ($share->getShareType() === IShare::TYPE_DECK) {
  1465. try {
  1466. return $this->getDeckShareHelper()->canAccessShare($share, $this->currentUser);
  1467. } catch (QueryException $e) {
  1468. return false;
  1469. }
  1470. }
  1471. if ($share->getShareType() === IShare::TYPE_SCIENCEMESH) {
  1472. try {
  1473. return $this->getSciencemeshShareHelper()->canAccessShare($share, $this->currentUser);
  1474. } catch (QueryException $e) {
  1475. return false;
  1476. }
  1477. }
  1478. return false;
  1479. }
  1480. /**
  1481. * Make sure that the passed date is valid ISO 8601
  1482. * So YYYY-MM-DD
  1483. * If not throw an exception
  1484. *
  1485. * @param string $expireDate
  1486. *
  1487. * @throws \Exception
  1488. * @return \DateTime
  1489. */
  1490. private function parseDate(string $expireDate): \DateTime {
  1491. try {
  1492. $date = new \DateTime(trim($expireDate, "\""));
  1493. } catch (\Exception $e) {
  1494. throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
  1495. }
  1496. $date->setTime(0, 0, 0);
  1497. return $date;
  1498. }
  1499. /**
  1500. * Since we have multiple providers but the OCS Share API v1 does
  1501. * not support this we need to check all backends.
  1502. *
  1503. * @param string $id
  1504. * @return \OCP\Share\IShare
  1505. * @throws ShareNotFound
  1506. */
  1507. private function getShareById(string $id): IShare {
  1508. $share = null;
  1509. // First check if it is an internal share.
  1510. try {
  1511. $share = $this->shareManager->getShareById('ocinternal:' . $id, $this->currentUser);
  1512. return $share;
  1513. } catch (ShareNotFound $e) {
  1514. // Do nothing, just try the other share type
  1515. }
  1516. try {
  1517. if ($this->shareManager->shareProviderExists(IShare::TYPE_CIRCLE)) {
  1518. $share = $this->shareManager->getShareById('ocCircleShare:' . $id, $this->currentUser);
  1519. return $share;
  1520. }
  1521. } catch (ShareNotFound $e) {
  1522. // Do nothing, just try the other share type
  1523. }
  1524. try {
  1525. if ($this->shareManager->shareProviderExists(IShare::TYPE_EMAIL)) {
  1526. $share = $this->shareManager->getShareById('ocMailShare:' . $id, $this->currentUser);
  1527. return $share;
  1528. }
  1529. } catch (ShareNotFound $e) {
  1530. // Do nothing, just try the other share type
  1531. }
  1532. try {
  1533. $share = $this->shareManager->getShareById('ocRoomShare:' . $id, $this->currentUser);
  1534. return $share;
  1535. } catch (ShareNotFound $e) {
  1536. // Do nothing, just try the other share type
  1537. }
  1538. try {
  1539. if ($this->shareManager->shareProviderExists(IShare::TYPE_DECK)) {
  1540. $share = $this->shareManager->getShareById('deck:' . $id, $this->currentUser);
  1541. return $share;
  1542. }
  1543. } catch (ShareNotFound $e) {
  1544. // Do nothing, just try the other share type
  1545. }
  1546. try {
  1547. if ($this->shareManager->shareProviderExists(IShare::TYPE_SCIENCEMESH)) {
  1548. $share = $this->shareManager->getShareById('sciencemesh:' . $id, $this->currentUser);
  1549. return $share;
  1550. }
  1551. } catch (ShareNotFound $e) {
  1552. // Do nothing, just try the other share type
  1553. }
  1554. if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
  1555. throw new ShareNotFound();
  1556. }
  1557. $share = $this->shareManager->getShareById('ocFederatedSharing:' . $id, $this->currentUser);
  1558. return $share;
  1559. }
  1560. /**
  1561. * Lock a Node
  1562. *
  1563. * @param \OCP\Files\Node $node
  1564. * @throws LockedException
  1565. */
  1566. private function lock(\OCP\Files\Node $node) {
  1567. $node->lock(ILockingProvider::LOCK_SHARED);
  1568. $this->lockedNode = $node;
  1569. }
  1570. /**
  1571. * Cleanup the remaining locks
  1572. * @throws LockedException
  1573. */
  1574. public function cleanup() {
  1575. if ($this->lockedNode !== null) {
  1576. $this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
  1577. }
  1578. }
  1579. /**
  1580. * Returns the helper of ShareAPIController for room shares.
  1581. *
  1582. * If the Talk application is not enabled or the helper is not available
  1583. * a QueryException is thrown instead.
  1584. *
  1585. * @return \OCA\Talk\Share\Helper\ShareAPIController
  1586. * @throws QueryException
  1587. */
  1588. private function getRoomShareHelper() {
  1589. if (!$this->appManager->isEnabledForUser('spreed')) {
  1590. throw new QueryException();
  1591. }
  1592. return $this->serverContainer->get('\OCA\Talk\Share\Helper\ShareAPIController');
  1593. }
  1594. /**
  1595. * Returns the helper of ShareAPIHelper for deck shares.
  1596. *
  1597. * If the Deck application is not enabled or the helper is not available
  1598. * a QueryException is thrown instead.
  1599. *
  1600. * @return \OCA\Deck\Sharing\ShareAPIHelper
  1601. * @throws QueryException
  1602. */
  1603. private function getDeckShareHelper() {
  1604. if (!$this->appManager->isEnabledForUser('deck')) {
  1605. throw new QueryException();
  1606. }
  1607. return $this->serverContainer->get('\OCA\Deck\Sharing\ShareAPIHelper');
  1608. }
  1609. /**
  1610. * Returns the helper of ShareAPIHelper for sciencemesh shares.
  1611. *
  1612. * If the sciencemesh application is not enabled or the helper is not available
  1613. * a QueryException is thrown instead.
  1614. *
  1615. * @return \OCA\Deck\Sharing\ShareAPIHelper
  1616. * @throws QueryException
  1617. */
  1618. private function getSciencemeshShareHelper() {
  1619. if (!$this->appManager->isEnabledForUser('sciencemesh')) {
  1620. throw new QueryException();
  1621. }
  1622. return $this->serverContainer->get('\OCA\ScienceMesh\Sharing\ShareAPIHelper');
  1623. }
  1624. /**
  1625. * @param string $viewer
  1626. * @param Node $node
  1627. * @param bool $reShares
  1628. *
  1629. * @return IShare[]
  1630. */
  1631. private function getSharesFromNode(string $viewer, $node, bool $reShares): array {
  1632. $providers = [
  1633. IShare::TYPE_USER,
  1634. IShare::TYPE_GROUP,
  1635. IShare::TYPE_LINK,
  1636. IShare::TYPE_EMAIL,
  1637. IShare::TYPE_CIRCLE,
  1638. IShare::TYPE_ROOM,
  1639. IShare::TYPE_DECK,
  1640. IShare::TYPE_SCIENCEMESH
  1641. ];
  1642. // Should we assume that the (currentUser) viewer is the owner of the node !?
  1643. $shares = [];
  1644. foreach ($providers as $provider) {
  1645. if (!$this->shareManager->shareProviderExists($provider)) {
  1646. continue;
  1647. }
  1648. $providerShares =
  1649. $this->shareManager->getSharesBy($viewer, $provider, $node, $reShares, -1, 0);
  1650. $shares = array_merge($shares, $providerShares);
  1651. }
  1652. if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
  1653. $federatedShares = $this->shareManager->getSharesBy(
  1654. $this->currentUser, IShare::TYPE_REMOTE, $node, $reShares, -1, 0
  1655. );
  1656. $shares = array_merge($shares, $federatedShares);
  1657. }
  1658. if ($this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
  1659. $federatedShares = $this->shareManager->getSharesBy(
  1660. $this->currentUser, IShare::TYPE_REMOTE_GROUP, $node, $reShares, -1, 0
  1661. );
  1662. $shares = array_merge($shares, $federatedShares);
  1663. }
  1664. return $shares;
  1665. }
  1666. /**
  1667. * @param Node $node
  1668. *
  1669. * @throws SharingRightsException
  1670. */
  1671. private function confirmSharingRights(Node $node): void {
  1672. if (!$this->hasResharingRights($this->currentUser, $node)) {
  1673. throw new SharingRightsException('no sharing rights on this item');
  1674. }
  1675. }
  1676. /**
  1677. * @param string $viewer
  1678. * @param Node $node
  1679. *
  1680. * @return bool
  1681. */
  1682. private function hasResharingRights($viewer, $node): bool {
  1683. if ($viewer === $node->getOwner()->getUID()) {
  1684. return true;
  1685. }
  1686. foreach ([$node, $node->getParent()] as $node) {
  1687. $shares = $this->getSharesFromNode($viewer, $node, true);
  1688. foreach ($shares as $share) {
  1689. try {
  1690. if ($this->shareProviderResharingRights($viewer, $share, $node)) {
  1691. return true;
  1692. }
  1693. } catch (InvalidPathException | NotFoundException $e) {
  1694. }
  1695. }
  1696. }
  1697. return false;
  1698. }
  1699. /**
  1700. * Returns if we can find resharing rights in an IShare object for a specific user.
  1701. *
  1702. * @suppress PhanUndeclaredClassMethod
  1703. *
  1704. * @param string $userId
  1705. * @param IShare $share
  1706. * @param Node $node
  1707. *
  1708. * @return bool
  1709. * @throws NotFoundException
  1710. * @throws InvalidPathException
  1711. */
  1712. private function shareProviderResharingRights(string $userId, IShare $share, $node): bool {
  1713. if ($share->getShareOwner() === $userId) {
  1714. return true;
  1715. }
  1716. // we check that current user have parent resharing rights on the current file
  1717. if ($node !== null && ($node->getPermissions() & Constants::PERMISSION_SHARE) !== 0) {
  1718. return true;
  1719. }
  1720. if ((\OCP\Constants::PERMISSION_SHARE & $share->getPermissions()) === 0) {
  1721. return false;
  1722. }
  1723. if ($share->getShareType() === IShare::TYPE_USER && $share->getSharedWith() === $userId) {
  1724. return true;
  1725. }
  1726. if ($share->getShareType() === IShare::TYPE_GROUP && $this->groupManager->isInGroup($userId, $share->getSharedWith())) {
  1727. return true;
  1728. }
  1729. if ($share->getShareType() === IShare::TYPE_CIRCLE && \OC::$server->getAppManager()->isEnabledForUser('circles')
  1730. && class_exists('\OCA\Circles\Api\v1\Circles')) {
  1731. $hasCircleId = (str_ends_with($share->getSharedWith(), ']'));
  1732. $shareWithStart = ($hasCircleId ? strrpos($share->getSharedWith(), '[') + 1 : 0);
  1733. $shareWithLength = ($hasCircleId ? -1 : strpos($share->getSharedWith(), ' '));
  1734. if ($shareWithLength === false) {
  1735. $sharedWith = substr($share->getSharedWith(), $shareWithStart);
  1736. } else {
  1737. $sharedWith = substr($share->getSharedWith(), $shareWithStart, $shareWithLength);
  1738. }
  1739. try {
  1740. $member = \OCA\Circles\Api\v1\Circles::getMember($sharedWith, $userId, 1);
  1741. if ($member->getLevel() >= 4) {
  1742. return true;
  1743. }
  1744. return false;
  1745. } catch (QueryException $e) {
  1746. return false;
  1747. }
  1748. }
  1749. return false;
  1750. }
  1751. /**
  1752. * Get all the shares for the current user
  1753. *
  1754. * @param Node|null $path
  1755. * @param boolean $reshares
  1756. * @return IShare[]
  1757. */
  1758. private function getAllShares(?Node $path = null, bool $reshares = false) {
  1759. // Get all shares
  1760. $userShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_USER, $path, $reshares, -1, 0);
  1761. $groupShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_GROUP, $path, $reshares, -1, 0);
  1762. $linkShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_LINK, $path, $reshares, -1, 0);
  1763. // EMAIL SHARES
  1764. $mailShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_EMAIL, $path, $reshares, -1, 0);
  1765. // CIRCLE SHARES
  1766. $circleShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_CIRCLE, $path, $reshares, -1, 0);
  1767. // TALK SHARES
  1768. $roomShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_ROOM, $path, $reshares, -1, 0);
  1769. // DECK SHARES
  1770. $deckShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_DECK, $path, $reshares, -1, 0);
  1771. // SCIENCEMESH SHARES
  1772. $sciencemeshShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_SCIENCEMESH, $path, $reshares, -1, 0);
  1773. // FEDERATION
  1774. if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
  1775. $federatedShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_REMOTE, $path, $reshares, -1, 0);
  1776. } else {
  1777. $federatedShares = [];
  1778. }
  1779. if ($this->shareManager->outgoingServer2ServerGroupSharesAllowed()) {
  1780. $federatedGroupShares = $this->shareManager->getSharesBy($this->currentUser, IShare::TYPE_REMOTE_GROUP, $path, $reshares, -1, 0);
  1781. } else {
  1782. $federatedGroupShares = [];
  1783. }
  1784. return array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares, $roomShares, $deckShares, $sciencemeshShares, $federatedShares, $federatedGroupShares);
  1785. }
  1786. /**
  1787. * merging already formatted shares.
  1788. * We'll make an associative array to easily detect duplicate Ids.
  1789. * Keys _needs_ to be removed after all shares are retrieved and merged.
  1790. *
  1791. * @param array $shares
  1792. * @param array $newShares
  1793. */
  1794. private function mergeFormattedShares(array &$shares, array $newShares) {
  1795. foreach ($newShares as $newShare) {
  1796. if (!array_key_exists($newShare['id'], $shares)) {
  1797. $shares[$newShare['id']] = $newShare;
  1798. }
  1799. }
  1800. }
  1801. /**
  1802. * @param IShare $share
  1803. * @param string|null $attributesString
  1804. * @return IShare modified share
  1805. */
  1806. private function setShareAttributes(IShare $share, ?string $attributesString) {
  1807. $newShareAttributes = null;
  1808. if ($attributesString !== null) {
  1809. $newShareAttributes = $this->shareManager->newShare()->newAttributes();
  1810. $formattedShareAttributes = \json_decode($attributesString, true);
  1811. if (is_array($formattedShareAttributes)) {
  1812. foreach ($formattedShareAttributes as $formattedAttr) {
  1813. $newShareAttributes->setAttribute(
  1814. $formattedAttr['scope'],
  1815. $formattedAttr['key'],
  1816. is_string($formattedAttr['enabled']) ? (bool) \json_decode($formattedAttr['enabled']) : $formattedAttr['enabled']
  1817. );
  1818. }
  1819. } else {
  1820. throw new OCSBadRequestException('Invalid share attributes provided: \"' . $attributesString . '\"');
  1821. }
  1822. }
  1823. $share->setAttributes($newShareAttributes);
  1824. return $share;
  1825. }
  1826. private function checkInheritedAttributes(IShare $share): void {
  1827. if (!$share->getSharedBy()) {
  1828. return; // Probably in a test
  1829. }
  1830. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  1831. $nodes = $userFolder->getById($share->getNodeId());
  1832. if (empty($nodes)) {
  1833. return;
  1834. }
  1835. $node = $nodes[0];
  1836. if ($node->getStorage()->instanceOfStorage(SharedStorage::class)) {
  1837. $storage = $node->getStorage();
  1838. if ($storage instanceof Wrapper) {
  1839. $storage = $storage->getInstanceOfStorage(SharedStorage::class);
  1840. if ($storage === null) {
  1841. throw new \RuntimeException('Should not happen, instanceOfStorage but getInstanceOfStorage return null');
  1842. }
  1843. } else {
  1844. throw new \RuntimeException('Should not happen, instanceOfStorage but not a wrapper');
  1845. }
  1846. /** @var \OCA\Files_Sharing\SharedStorage $storage */
  1847. $inheritedAttributes = $storage->getShare()->getAttributes();
  1848. if ($inheritedAttributes !== null && $inheritedAttributes->getAttribute('permissions', 'download') === false) {
  1849. $share->setHideDownload(true);
  1850. $attributes = $share->getAttributes();
  1851. if ($attributes) {
  1852. $attributes->setAttribute('permissions', 'download', false);
  1853. $share->setAttributes($attributes);
  1854. }
  1855. }
  1856. }
  1857. }
  1858. }