ShareAPIController.php 67 KB

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