ShareAPIController.php 55 KB

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