You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ShareAPIController.php 67KB

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