ShareAPIController.php 63 KB

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