Manager.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. * @author Vincent Petry <pvince81@owncloud.com>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OC\Share20;
  28. use OC\Cache\CappedMemoryCache;
  29. use OC\Files\Mount\MoveableMount;
  30. use OC\HintException;
  31. use OCP\Files\File;
  32. use OCP\Files\Folder;
  33. use OCP\Files\IRootFolder;
  34. use OCP\Files\Mount\IMountManager;
  35. use OCP\Files\NotFoundException;
  36. use OCP\IConfig;
  37. use OCP\IGroupManager;
  38. use OCP\IL10N;
  39. use OCP\ILogger;
  40. use OCP\IUserManager;
  41. use OCP\Security\IHasher;
  42. use OCP\Security\ISecureRandom;
  43. use OCP\Share\Exceptions\GenericShareException;
  44. use OCP\Share\Exceptions\ShareNotFound;
  45. use OCP\Share\IManager;
  46. use OCP\Share\IProviderFactory;
  47. use Symfony\Component\EventDispatcher\EventDispatcher;
  48. use Symfony\Component\EventDispatcher\GenericEvent;
  49. /**
  50. * This class is the communication hub for all sharing related operations.
  51. */
  52. class Manager implements IManager {
  53. /** @var IProviderFactory */
  54. private $factory;
  55. /** @var ILogger */
  56. private $logger;
  57. /** @var IConfig */
  58. private $config;
  59. /** @var ISecureRandom */
  60. private $secureRandom;
  61. /** @var IHasher */
  62. private $hasher;
  63. /** @var IMountManager */
  64. private $mountManager;
  65. /** @var IGroupManager */
  66. private $groupManager;
  67. /** @var IL10N */
  68. private $l;
  69. /** @var IUserManager */
  70. private $userManager;
  71. /** @var IRootFolder */
  72. private $rootFolder;
  73. /** @var CappedMemoryCache */
  74. private $sharingDisabledForUsersCache;
  75. /** @var EventDispatcher */
  76. private $eventDispatcher;
  77. /**
  78. * Manager constructor.
  79. *
  80. * @param ILogger $logger
  81. * @param IConfig $config
  82. * @param ISecureRandom $secureRandom
  83. * @param IHasher $hasher
  84. * @param IMountManager $mountManager
  85. * @param IGroupManager $groupManager
  86. * @param IL10N $l
  87. * @param IProviderFactory $factory
  88. * @param IUserManager $userManager
  89. * @param IRootFolder $rootFolder
  90. * @param EventDispatcher $eventDispatcher
  91. */
  92. public function __construct(
  93. ILogger $logger,
  94. IConfig $config,
  95. ISecureRandom $secureRandom,
  96. IHasher $hasher,
  97. IMountManager $mountManager,
  98. IGroupManager $groupManager,
  99. IL10N $l,
  100. IProviderFactory $factory,
  101. IUserManager $userManager,
  102. IRootFolder $rootFolder,
  103. EventDispatcher $eventDispatcher
  104. ) {
  105. $this->logger = $logger;
  106. $this->config = $config;
  107. $this->secureRandom = $secureRandom;
  108. $this->hasher = $hasher;
  109. $this->mountManager = $mountManager;
  110. $this->groupManager = $groupManager;
  111. $this->l = $l;
  112. $this->factory = $factory;
  113. $this->userManager = $userManager;
  114. $this->rootFolder = $rootFolder;
  115. $this->eventDispatcher = $eventDispatcher;
  116. $this->sharingDisabledForUsersCache = new CappedMemoryCache();
  117. }
  118. /**
  119. * Convert from a full share id to a tuple (providerId, shareId)
  120. *
  121. * @param string $id
  122. * @return string[]
  123. */
  124. private function splitFullId($id) {
  125. return explode(':', $id, 2);
  126. }
  127. /**
  128. * Verify if a password meets all requirements
  129. *
  130. * @param string $password
  131. * @throws \Exception
  132. */
  133. protected function verifyPassword($password) {
  134. if ($password === null) {
  135. // No password is set, check if this is allowed.
  136. if ($this->shareApiLinkEnforcePassword()) {
  137. throw new \InvalidArgumentException('Passwords are enforced for link shares');
  138. }
  139. return;
  140. }
  141. // Let others verify the password
  142. try {
  143. $event = new GenericEvent($password);
  144. $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
  145. } catch (HintException $e) {
  146. throw new \Exception($e->getHint());
  147. }
  148. }
  149. /**
  150. * Check for generic requirements before creating a share
  151. *
  152. * @param \OCP\Share\IShare $share
  153. * @throws \InvalidArgumentException
  154. * @throws GenericShareException
  155. */
  156. protected function generalCreateChecks(\OCP\Share\IShare $share) {
  157. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
  158. // We expect a valid user as sharedWith for user shares
  159. if (!$this->userManager->userExists($share->getSharedWith())) {
  160. throw new \InvalidArgumentException('SharedWith is not a valid user');
  161. }
  162. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
  163. // We expect a valid group as sharedWith for group shares
  164. if (!$this->groupManager->groupExists($share->getSharedWith())) {
  165. throw new \InvalidArgumentException('SharedWith is not a valid group');
  166. }
  167. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
  168. if ($share->getSharedWith() !== null) {
  169. throw new \InvalidArgumentException('SharedWith should be empty');
  170. }
  171. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
  172. if ($share->getSharedWith() === null) {
  173. throw new \InvalidArgumentException('SharedWith should not be empty');
  174. }
  175. } else {
  176. // We can't handle other types yet
  177. throw new \InvalidArgumentException('unkown share type');
  178. }
  179. // Verify the initiator of the share is set
  180. if ($share->getSharedBy() === null) {
  181. throw new \InvalidArgumentException('SharedBy should be set');
  182. }
  183. // Cannot share with yourself
  184. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
  185. $share->getSharedWith() === $share->getSharedBy()) {
  186. throw new \InvalidArgumentException('Can\'t share with yourself');
  187. }
  188. // The path should be set
  189. if ($share->getNode() === null) {
  190. throw new \InvalidArgumentException('Path should be set');
  191. }
  192. // And it should be a file or a folder
  193. if (!($share->getNode() instanceof \OCP\Files\File) &&
  194. !($share->getNode() instanceof \OCP\Files\Folder)) {
  195. throw new \InvalidArgumentException('Path should be either a file or a folder');
  196. }
  197. // And you can't share your rootfolder
  198. if ($this->userManager->userExists($share->getSharedBy())) {
  199. $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
  200. } else {
  201. $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
  202. }
  203. if ($sharedPath === $share->getNode()->getPath()) {
  204. throw new \InvalidArgumentException('You can\'t share your root folder');
  205. }
  206. // Check if we actually have share permissions
  207. if (!$share->getNode()->isShareable()) {
  208. $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
  209. throw new GenericShareException($message_t, $message_t, 404);
  210. }
  211. // Permissions should be set
  212. if ($share->getPermissions() === null) {
  213. throw new \InvalidArgumentException('A share requires permissions');
  214. }
  215. /*
  216. * Quick fix for #23536
  217. * Non moveable mount points do not have update and delete permissions
  218. * while we 'most likely' do have that on the storage.
  219. */
  220. $permissions = $share->getNode()->getPermissions();
  221. $mount = $share->getNode()->getMountPoint();
  222. if (!($mount instanceof MoveableMount)) {
  223. $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
  224. }
  225. // Check that we do not share with more permissions than we have
  226. if ($share->getPermissions() & ~$permissions) {
  227. $message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
  228. throw new GenericShareException($message_t, $message_t, 404);
  229. }
  230. // Check that read permissions are always set
  231. // Link shares are allowed to have no read permissions to allow upload to hidden folders
  232. if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK &&
  233. ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
  234. throw new \InvalidArgumentException('Shares need at least read permissions');
  235. }
  236. if ($share->getNode() instanceof \OCP\Files\File) {
  237. if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
  238. $message_t = $this->l->t('Files can\'t be shared with delete permissions');
  239. throw new GenericShareException($message_t);
  240. }
  241. if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
  242. $message_t = $this->l->t('Files can\'t be shared with create permissions');
  243. throw new GenericShareException($message_t);
  244. }
  245. }
  246. }
  247. /**
  248. * Validate if the expiration date fits the system settings
  249. *
  250. * @param \OCP\Share\IShare $share The share to validate the expiration date of
  251. * @return \OCP\Share\IShare The modified share object
  252. * @throws GenericShareException
  253. * @throws \InvalidArgumentException
  254. * @throws \Exception
  255. */
  256. protected function validateExpirationDate(\OCP\Share\IShare $share) {
  257. $expirationDate = $share->getExpirationDate();
  258. if ($expirationDate !== null) {
  259. //Make sure the expiration date is a date
  260. $expirationDate->setTime(0, 0, 0);
  261. $date = new \DateTime();
  262. $date->setTime(0, 0, 0);
  263. if ($date >= $expirationDate) {
  264. $message = $this->l->t('Expiration date is in the past');
  265. throw new GenericShareException($message, $message, 404);
  266. }
  267. }
  268. // If expiredate is empty set a default one if there is a default
  269. $fullId = null;
  270. try {
  271. $fullId = $share->getFullId();
  272. } catch (\UnexpectedValueException $e) {
  273. // This is a new share
  274. }
  275. if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
  276. $expirationDate = new \DateTime();
  277. $expirationDate->setTime(0,0,0);
  278. $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
  279. }
  280. // If we enforce the expiration date check that is does not exceed
  281. if ($this->shareApiLinkDefaultExpireDateEnforced()) {
  282. if ($expirationDate === null) {
  283. throw new \InvalidArgumentException('Expiration date is enforced');
  284. }
  285. $date = new \DateTime();
  286. $date->setTime(0, 0, 0);
  287. $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
  288. if ($date < $expirationDate) {
  289. $message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
  290. throw new GenericShareException($message, $message, 404);
  291. }
  292. }
  293. $accepted = true;
  294. $message = '';
  295. \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
  296. 'expirationDate' => &$expirationDate,
  297. 'accepted' => &$accepted,
  298. 'message' => &$message,
  299. 'passwordSet' => $share->getPassword() !== null,
  300. ]);
  301. if (!$accepted) {
  302. throw new \Exception($message);
  303. }
  304. $share->setExpirationDate($expirationDate);
  305. return $share;
  306. }
  307. /**
  308. * Check for pre share requirements for user shares
  309. *
  310. * @param \OCP\Share\IShare $share
  311. * @throws \Exception
  312. */
  313. protected function userCreateChecks(\OCP\Share\IShare $share) {
  314. // Check if we can share with group members only
  315. if ($this->shareWithGroupMembersOnly()) {
  316. $sharedBy = $this->userManager->get($share->getSharedBy());
  317. $sharedWith = $this->userManager->get($share->getSharedWith());
  318. // Verify we can share with this user
  319. $groups = array_intersect(
  320. $this->groupManager->getUserGroupIds($sharedBy),
  321. $this->groupManager->getUserGroupIds($sharedWith)
  322. );
  323. if (empty($groups)) {
  324. throw new \Exception('Only sharing with group members is allowed');
  325. }
  326. }
  327. /*
  328. * TODO: Could be costly, fix
  329. *
  330. * Also this is not what we want in the future.. then we want to squash identical shares.
  331. */
  332. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
  333. $existingShares = $provider->getSharesByPath($share->getNode());
  334. foreach($existingShares as $existingShare) {
  335. // Ignore if it is the same share
  336. try {
  337. if ($existingShare->getFullId() === $share->getFullId()) {
  338. continue;
  339. }
  340. } catch (\UnexpectedValueException $e) {
  341. //Shares are not identical
  342. }
  343. // Identical share already existst
  344. if ($existingShare->getSharedWith() === $share->getSharedWith()) {
  345. throw new \Exception('Path already shared with this user');
  346. }
  347. // The share is already shared with this user via a group share
  348. if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
  349. $group = $this->groupManager->get($existingShare->getSharedWith());
  350. $user = $this->userManager->get($share->getSharedWith());
  351. if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
  352. throw new \Exception('Path already shared with this user');
  353. }
  354. }
  355. }
  356. }
  357. /**
  358. * Check for pre share requirements for group shares
  359. *
  360. * @param \OCP\Share\IShare $share
  361. * @throws \Exception
  362. */
  363. protected function groupCreateChecks(\OCP\Share\IShare $share) {
  364. // Verify group shares are allowed
  365. if (!$this->allowGroupSharing()) {
  366. throw new \Exception('Group sharing is now allowed');
  367. }
  368. // Verify if the user can share with this group
  369. if ($this->shareWithGroupMembersOnly()) {
  370. $sharedBy = $this->userManager->get($share->getSharedBy());
  371. $sharedWith = $this->groupManager->get($share->getSharedWith());
  372. if (!$sharedWith->inGroup($sharedBy)) {
  373. throw new \Exception('Only sharing within your own groups is allowed');
  374. }
  375. }
  376. /*
  377. * TODO: Could be costly, fix
  378. *
  379. * Also this is not what we want in the future.. then we want to squash identical shares.
  380. */
  381. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
  382. $existingShares = $provider->getSharesByPath($share->getNode());
  383. foreach($existingShares as $existingShare) {
  384. try {
  385. if ($existingShare->getFullId() === $share->getFullId()) {
  386. continue;
  387. }
  388. } catch (\UnexpectedValueException $e) {
  389. //It is a new share so just continue
  390. }
  391. if ($existingShare->getSharedWith() === $share->getSharedWith()) {
  392. throw new \Exception('Path already shared with this group');
  393. }
  394. }
  395. }
  396. /**
  397. * Check for pre share requirements for link shares
  398. *
  399. * @param \OCP\Share\IShare $share
  400. * @throws \Exception
  401. */
  402. protected function linkCreateChecks(\OCP\Share\IShare $share) {
  403. // Are link shares allowed?
  404. if (!$this->shareApiAllowLinks()) {
  405. throw new \Exception('Link sharing not allowed');
  406. }
  407. // Link shares by definition can't have share permissions
  408. if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
  409. throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
  410. }
  411. // Check if public upload is allowed
  412. if (!$this->shareApiLinkAllowPublicUpload() &&
  413. ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
  414. throw new \InvalidArgumentException('Public upload not allowed');
  415. }
  416. }
  417. /**
  418. * To make sure we don't get invisible link shares we set the parent
  419. * of a link if it is a reshare. This is a quick word around
  420. * until we can properly display multiple link shares in the UI
  421. *
  422. * See: https://github.com/owncloud/core/issues/22295
  423. *
  424. * FIXME: Remove once multiple link shares can be properly displayed
  425. *
  426. * @param \OCP\Share\IShare $share
  427. */
  428. protected function setLinkParent(\OCP\Share\IShare $share) {
  429. // No sense in checking if the method is not there.
  430. if (method_exists($share, 'setParent')) {
  431. $storage = $share->getNode()->getStorage();
  432. if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
  433. $share->setParent($storage->getShareId());
  434. }
  435. };
  436. }
  437. /**
  438. * @param File|Folder $path
  439. */
  440. protected function pathCreateChecks($path) {
  441. // Make sure that we do not share a path that contains a shared mountpoint
  442. if ($path instanceof \OCP\Files\Folder) {
  443. $mounts = $this->mountManager->findIn($path->getPath());
  444. foreach($mounts as $mount) {
  445. if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
  446. throw new \InvalidArgumentException('Path contains files shared with you');
  447. }
  448. }
  449. }
  450. }
  451. /**
  452. * Check if the user that is sharing can actually share
  453. *
  454. * @param \OCP\Share\IShare $share
  455. * @throws \Exception
  456. */
  457. protected function canShare(\OCP\Share\IShare $share) {
  458. if (!$this->shareApiEnabled()) {
  459. throw new \Exception('The share API is disabled');
  460. }
  461. if ($this->sharingDisabledForUser($share->getSharedBy())) {
  462. throw new \Exception('You are not allowed to share');
  463. }
  464. }
  465. /**
  466. * Share a path
  467. *
  468. * @param \OCP\Share\IShare $share
  469. * @return Share The share object
  470. * @throws \Exception
  471. *
  472. * TODO: handle link share permissions or check them
  473. */
  474. public function createShare(\OCP\Share\IShare $share) {
  475. $this->canShare($share);
  476. $this->generalCreateChecks($share);
  477. // Verify if there are any issues with the path
  478. $this->pathCreateChecks($share->getNode());
  479. /*
  480. * On creation of a share the owner is always the owner of the path
  481. * Except for mounted federated shares.
  482. */
  483. $storage = $share->getNode()->getStorage();
  484. if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
  485. $parent = $share->getNode()->getParent();
  486. while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
  487. $parent = $parent->getParent();
  488. }
  489. $share->setShareOwner($parent->getOwner()->getUID());
  490. } else {
  491. $share->setShareOwner($share->getNode()->getOwner()->getUID());
  492. }
  493. //Verify share type
  494. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
  495. $this->userCreateChecks($share);
  496. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
  497. $this->groupCreateChecks($share);
  498. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
  499. $this->linkCreateChecks($share);
  500. $this->setLinkParent($share);
  501. /*
  502. * For now ignore a set token.
  503. */
  504. $share->setToken(
  505. $this->secureRandom->generate(
  506. \OC\Share\Constants::TOKEN_LENGTH,
  507. \OCP\Security\ISecureRandom::CHAR_LOWER.
  508. \OCP\Security\ISecureRandom::CHAR_UPPER.
  509. \OCP\Security\ISecureRandom::CHAR_DIGITS
  510. )
  511. );
  512. //Verify the expiration date
  513. $this->validateExpirationDate($share);
  514. //Verify the password
  515. $this->verifyPassword($share->getPassword());
  516. // If a password is set. Hash it!
  517. if ($share->getPassword() !== null) {
  518. $share->setPassword($this->hasher->hash($share->getPassword()));
  519. }
  520. }
  521. // Cannot share with the owner
  522. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
  523. $share->getSharedWith() === $share->getShareOwner()) {
  524. throw new \InvalidArgumentException('Can\'t share with the share owner');
  525. }
  526. // Generate the target
  527. $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
  528. $target = \OC\Files\Filesystem::normalizePath($target);
  529. $share->setTarget($target);
  530. // Pre share hook
  531. $run = true;
  532. $error = '';
  533. $preHookData = [
  534. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  535. 'itemSource' => $share->getNode()->getId(),
  536. 'shareType' => $share->getShareType(),
  537. 'uidOwner' => $share->getSharedBy(),
  538. 'permissions' => $share->getPermissions(),
  539. 'fileSource' => $share->getNode()->getId(),
  540. 'expiration' => $share->getExpirationDate(),
  541. 'token' => $share->getToken(),
  542. 'itemTarget' => $share->getTarget(),
  543. 'shareWith' => $share->getSharedWith(),
  544. 'run' => &$run,
  545. 'error' => &$error,
  546. ];
  547. \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
  548. if ($run === false) {
  549. throw new \Exception($error);
  550. }
  551. $provider = $this->factory->getProviderForType($share->getShareType());
  552. $share = $provider->create($share);
  553. // Post share hook
  554. $postHookData = [
  555. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  556. 'itemSource' => $share->getNode()->getId(),
  557. 'shareType' => $share->getShareType(),
  558. 'uidOwner' => $share->getSharedBy(),
  559. 'permissions' => $share->getPermissions(),
  560. 'fileSource' => $share->getNode()->getId(),
  561. 'expiration' => $share->getExpirationDate(),
  562. 'token' => $share->getToken(),
  563. 'id' => $share->getId(),
  564. 'shareWith' => $share->getSharedWith(),
  565. 'itemTarget' => $share->getTarget(),
  566. 'fileTarget' => $share->getTarget(),
  567. ];
  568. \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
  569. return $share;
  570. }
  571. /**
  572. * Update a share
  573. *
  574. * @param \OCP\Share\IShare $share
  575. * @return \OCP\Share\IShare The share object
  576. * @throws \InvalidArgumentException
  577. */
  578. public function updateShare(\OCP\Share\IShare $share) {
  579. $expirationDateUpdated = false;
  580. $this->canShare($share);
  581. try {
  582. $originalShare = $this->getShareById($share->getFullId());
  583. } catch (\UnexpectedValueException $e) {
  584. throw new \InvalidArgumentException('Share does not have a full id');
  585. }
  586. // We can't change the share type!
  587. if ($share->getShareType() !== $originalShare->getShareType()) {
  588. throw new \InvalidArgumentException('Can\'t change share type');
  589. }
  590. // We can only change the recipient on user shares
  591. if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
  592. $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
  593. throw new \InvalidArgumentException('Can only update recipient on user shares');
  594. }
  595. // Cannot share with the owner
  596. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
  597. $share->getSharedWith() === $share->getShareOwner()) {
  598. throw new \InvalidArgumentException('Can\'t share with the share owner');
  599. }
  600. $this->generalCreateChecks($share);
  601. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
  602. $this->userCreateChecks($share);
  603. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
  604. $this->groupCreateChecks($share);
  605. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
  606. $this->linkCreateChecks($share);
  607. // Password updated.
  608. if ($share->getPassword() !== $originalShare->getPassword()) {
  609. //Verify the password
  610. $this->verifyPassword($share->getPassword());
  611. // If a password is set. Hash it!
  612. if ($share->getPassword() !== null) {
  613. $share->setPassword($this->hasher->hash($share->getPassword()));
  614. }
  615. }
  616. if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
  617. //Verify the expiration date
  618. $this->validateExpirationDate($share);
  619. $expirationDateUpdated = true;
  620. }
  621. }
  622. $this->pathCreateChecks($share->getNode());
  623. // Now update the share!
  624. $provider = $this->factory->getProviderForType($share->getShareType());
  625. $share = $provider->update($share);
  626. if ($expirationDateUpdated === true) {
  627. \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
  628. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  629. 'itemSource' => $share->getNode()->getId(),
  630. 'date' => $share->getExpirationDate(),
  631. 'uidOwner' => $share->getSharedBy(),
  632. ]);
  633. }
  634. if ($share->getPassword() !== $originalShare->getPassword()) {
  635. \OC_Hook::emit('OCP\Share', 'post_update_password', [
  636. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  637. 'itemSource' => $share->getNode()->getId(),
  638. 'uidOwner' => $share->getSharedBy(),
  639. 'token' => $share->getToken(),
  640. 'disabled' => is_null($share->getPassword()),
  641. ]);
  642. }
  643. if ($share->getPermissions() !== $originalShare->getPermissions()) {
  644. if ($this->userManager->userExists($share->getShareOwner())) {
  645. $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  646. } else {
  647. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  648. }
  649. \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
  650. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  651. 'itemSource' => $share->getNode()->getId(),
  652. 'shareType' => $share->getShareType(),
  653. 'shareWith' => $share->getSharedWith(),
  654. 'uidOwner' => $share->getSharedBy(),
  655. 'permissions' => $share->getPermissions(),
  656. 'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
  657. ));
  658. }
  659. return $share;
  660. }
  661. /**
  662. * Delete all the children of this share
  663. * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
  664. *
  665. * @param \OCP\Share\IShare $share
  666. * @return \OCP\Share\IShare[] List of deleted shares
  667. */
  668. protected function deleteChildren(\OCP\Share\IShare $share) {
  669. $deletedShares = [];
  670. $provider = $this->factory->getProviderForType($share->getShareType());
  671. foreach ($provider->getChildren($share) as $child) {
  672. $deletedChildren = $this->deleteChildren($child);
  673. $deletedShares = array_merge($deletedShares, $deletedChildren);
  674. $provider->delete($child);
  675. $deletedShares[] = $child;
  676. }
  677. return $deletedShares;
  678. }
  679. /**
  680. * Delete a share
  681. *
  682. * @param \OCP\Share\IShare $share
  683. * @throws ShareNotFound
  684. * @throws \InvalidArgumentException
  685. */
  686. public function deleteShare(\OCP\Share\IShare $share) {
  687. try {
  688. $share->getFullId();
  689. } catch (\UnexpectedValueException $e) {
  690. throw new \InvalidArgumentException('Share does not have a full id');
  691. }
  692. $formatHookParams = function(\OCP\Share\IShare $share) {
  693. // Prepare hook
  694. $shareType = $share->getShareType();
  695. $sharedWith = '';
  696. if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
  697. $sharedWith = $share->getSharedWith();
  698. } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
  699. $sharedWith = $share->getSharedWith();
  700. } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
  701. $sharedWith = $share->getSharedWith();
  702. }
  703. $hookParams = [
  704. 'id' => $share->getId(),
  705. 'itemType' => $share->getNodeType(),
  706. 'itemSource' => $share->getNodeId(),
  707. 'shareType' => $shareType,
  708. 'shareWith' => $sharedWith,
  709. 'itemparent' => method_exists($share, 'getParent') ? $share->getParent() : '',
  710. 'uidOwner' => $share->getSharedBy(),
  711. 'fileSource' => $share->getNodeId(),
  712. 'fileTarget' => $share->getTarget()
  713. ];
  714. return $hookParams;
  715. };
  716. $hookParams = $formatHookParams($share);
  717. // Emit pre-hook
  718. \OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
  719. // Get all children and delete them as well
  720. $deletedShares = $this->deleteChildren($share);
  721. // Do the actual delete
  722. $provider = $this->factory->getProviderForType($share->getShareType());
  723. $provider->delete($share);
  724. // All the deleted shares caused by this delete
  725. $deletedShares[] = $share;
  726. //Format hook info
  727. $formattedDeletedShares = array_map(function($share) use ($formatHookParams) {
  728. return $formatHookParams($share);
  729. }, $deletedShares);
  730. $hookParams['deletedShares'] = $formattedDeletedShares;
  731. // Emit post hook
  732. \OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
  733. }
  734. /**
  735. * Unshare a file as the recipient.
  736. * This can be different from a regular delete for example when one of
  737. * the users in a groups deletes that share. But the provider should
  738. * handle this.
  739. *
  740. * @param \OCP\Share\IShare $share
  741. * @param string $recipientId
  742. */
  743. public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
  744. list($providerId, ) = $this->splitFullId($share->getFullId());
  745. $provider = $this->factory->getProvider($providerId);
  746. $provider->deleteFromSelf($share, $recipientId);
  747. }
  748. /**
  749. * @inheritdoc
  750. */
  751. public function moveShare(\OCP\Share\IShare $share, $recipientId) {
  752. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
  753. throw new \InvalidArgumentException('Can\'t change target of link share');
  754. }
  755. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
  756. throw new \InvalidArgumentException('Invalid recipient');
  757. }
  758. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
  759. $sharedWith = $this->groupManager->get($share->getSharedWith());
  760. $recipient = $this->userManager->get($recipientId);
  761. if (!$sharedWith->inGroup($recipient)) {
  762. throw new \InvalidArgumentException('Invalid recipient');
  763. }
  764. }
  765. list($providerId, ) = $this->splitFullId($share->getFullId());
  766. $provider = $this->factory->getProvider($providerId);
  767. $provider->move($share, $recipientId);
  768. }
  769. /**
  770. * @inheritdoc
  771. */
  772. public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
  773. if ($path !== null &&
  774. !($path instanceof \OCP\Files\File) &&
  775. !($path instanceof \OCP\Files\Folder)) {
  776. throw new \InvalidArgumentException('invalid path');
  777. }
  778. $provider = $this->factory->getProviderForType($shareType);
  779. $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
  780. /*
  781. * Work around so we don't return expired shares but still follow
  782. * proper pagination.
  783. */
  784. if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
  785. $shares2 = [];
  786. $today = new \DateTime();
  787. while(true) {
  788. $added = 0;
  789. foreach ($shares as $share) {
  790. // Check if the share is expired and if so delete it
  791. if ($share->getExpirationDate() !== null &&
  792. $share->getExpirationDate() <= $today
  793. ) {
  794. try {
  795. $this->deleteShare($share);
  796. } catch (NotFoundException $e) {
  797. //Ignore since this basically means the share is deleted
  798. }
  799. continue;
  800. }
  801. $added++;
  802. $shares2[] = $share;
  803. if (count($shares2) === $limit) {
  804. break;
  805. }
  806. }
  807. if (count($shares2) === $limit) {
  808. break;
  809. }
  810. // If there was no limit on the select we are done
  811. if ($limit === -1) {
  812. break;
  813. }
  814. $offset += $added;
  815. // Fetch again $limit shares
  816. $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
  817. // No more shares means we are done
  818. if (empty($shares)) {
  819. break;
  820. }
  821. }
  822. $shares = $shares2;
  823. }
  824. return $shares;
  825. }
  826. /**
  827. * @inheritdoc
  828. */
  829. public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
  830. $provider = $this->factory->getProviderForType($shareType);
  831. return $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
  832. }
  833. /**
  834. * @inheritdoc
  835. */
  836. public function getShareById($id, $recipient = null) {
  837. if ($id === null) {
  838. throw new ShareNotFound();
  839. }
  840. list($providerId, $id) = $this->splitFullId($id);
  841. $provider = $this->factory->getProvider($providerId);
  842. $share = $provider->getShareById($id, $recipient);
  843. // Validate link shares expiration date
  844. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
  845. $share->getExpirationDate() !== null &&
  846. $share->getExpirationDate() <= new \DateTime()) {
  847. $this->deleteShare($share);
  848. throw new ShareNotFound();
  849. }
  850. return $share;
  851. }
  852. /**
  853. * Get all the shares for a given path
  854. *
  855. * @param \OCP\Files\Node $path
  856. * @param int $page
  857. * @param int $perPage
  858. *
  859. * @return Share[]
  860. */
  861. public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
  862. }
  863. /**
  864. * Get the share by token possible with password
  865. *
  866. * @param string $token
  867. * @return Share
  868. *
  869. * @throws ShareNotFound
  870. */
  871. public function getShareByToken($token) {
  872. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
  873. try {
  874. $share = $provider->getShareByToken($token);
  875. } catch (ShareNotFound $e) {
  876. $share = null;
  877. }
  878. // If it is not a link share try to fetch a federated share by token
  879. if ($share === null) {
  880. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
  881. $share = $provider->getShareByToken($token);
  882. }
  883. if ($share->getExpirationDate() !== null &&
  884. $share->getExpirationDate() <= new \DateTime()) {
  885. $this->deleteShare($share);
  886. throw new ShareNotFound();
  887. }
  888. /*
  889. * Reduce the permissions for link shares if public upload is not enabled
  890. */
  891. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
  892. !$this->shareApiLinkAllowPublicUpload()) {
  893. $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
  894. }
  895. return $share;
  896. }
  897. /**
  898. * Verify the password of a public share
  899. *
  900. * @param \OCP\Share\IShare $share
  901. * @param string $password
  902. * @return bool
  903. */
  904. public function checkPassword(\OCP\Share\IShare $share, $password) {
  905. if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK) {
  906. //TODO maybe exception?
  907. return false;
  908. }
  909. if ($password === null || $share->getPassword() === null) {
  910. return false;
  911. }
  912. $newHash = '';
  913. if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
  914. return false;
  915. }
  916. if (!empty($newHash)) {
  917. $share->setPassword($newHash);
  918. $provider = $this->factory->getProviderForType($share->getShareType());
  919. $provider->update($share);
  920. }
  921. return true;
  922. }
  923. /**
  924. * @inheritdoc
  925. */
  926. public function userDeleted($uid) {
  927. $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE];
  928. foreach ($types as $type) {
  929. $provider = $this->factory->getProviderForType($type);
  930. $provider->userDeleted($uid, $type);
  931. }
  932. }
  933. /**
  934. * @inheritdoc
  935. */
  936. public function groupDeleted($gid) {
  937. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
  938. $provider->groupDeleted($gid);
  939. }
  940. /**
  941. * @inheritdoc
  942. */
  943. public function userDeletedFromGroup($uid, $gid) {
  944. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
  945. $provider->userDeletedFromGroup($uid, $gid);
  946. }
  947. /**
  948. * Get access list to a path. This means
  949. * all the users and groups that can access a given path.
  950. *
  951. * Consider:
  952. * -root
  953. * |-folder1
  954. * |-folder2
  955. * |-fileA
  956. *
  957. * fileA is shared with user1
  958. * folder2 is shared with group2
  959. * folder1 is shared with user2
  960. *
  961. * Then the access list will to '/folder1/folder2/fileA' is:
  962. * [
  963. * 'users' => ['user1', 'user2'],
  964. * 'groups' => ['group2']
  965. * ]
  966. *
  967. * This is required for encryption
  968. *
  969. * @param \OCP\Files\Node $path
  970. */
  971. public function getAccessList(\OCP\Files\Node $path) {
  972. }
  973. /**
  974. * Create a new share
  975. * @return \OCP\Share\IShare;
  976. */
  977. public function newShare() {
  978. return new \OC\Share20\Share($this->rootFolder, $this->userManager);
  979. }
  980. /**
  981. * Is the share API enabled
  982. *
  983. * @return bool
  984. */
  985. public function shareApiEnabled() {
  986. return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
  987. }
  988. /**
  989. * Is public link sharing enabled
  990. *
  991. * @return bool
  992. */
  993. public function shareApiAllowLinks() {
  994. return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
  995. }
  996. /**
  997. * Is password on public link requires
  998. *
  999. * @return bool
  1000. */
  1001. public function shareApiLinkEnforcePassword() {
  1002. return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
  1003. }
  1004. /**
  1005. * Is default expire date enabled
  1006. *
  1007. * @return bool
  1008. */
  1009. public function shareApiLinkDefaultExpireDate() {
  1010. return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
  1011. }
  1012. /**
  1013. * Is default expire date enforced
  1014. *`
  1015. * @return bool
  1016. */
  1017. public function shareApiLinkDefaultExpireDateEnforced() {
  1018. return $this->shareApiLinkDefaultExpireDate() &&
  1019. $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
  1020. }
  1021. /**
  1022. * Number of default expire days
  1023. *shareApiLinkAllowPublicUpload
  1024. * @return int
  1025. */
  1026. public function shareApiLinkDefaultExpireDays() {
  1027. return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
  1028. }
  1029. /**
  1030. * Allow public upload on link shares
  1031. *
  1032. * @return bool
  1033. */
  1034. public function shareApiLinkAllowPublicUpload() {
  1035. return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
  1036. }
  1037. /**
  1038. * check if user can only share with group members
  1039. * @return bool
  1040. */
  1041. public function shareWithGroupMembersOnly() {
  1042. return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
  1043. }
  1044. /**
  1045. * Check if users can share with groups
  1046. * @return bool
  1047. */
  1048. public function allowGroupSharing() {
  1049. return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
  1050. }
  1051. /**
  1052. * Copied from \OC_Util::isSharingDisabledForUser
  1053. *
  1054. * TODO: Deprecate fuction from OC_Util
  1055. *
  1056. * @param string $userId
  1057. * @return bool
  1058. */
  1059. public function sharingDisabledForUser($userId) {
  1060. if ($userId === null) {
  1061. return false;
  1062. }
  1063. if (isset($this->sharingDisabledForUsersCache[$userId])) {
  1064. return $this->sharingDisabledForUsersCache[$userId];
  1065. }
  1066. if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
  1067. $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
  1068. $excludedGroups = json_decode($groupsList);
  1069. if (is_null($excludedGroups)) {
  1070. $excludedGroups = explode(',', $groupsList);
  1071. $newValue = json_encode($excludedGroups);
  1072. $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
  1073. }
  1074. $user = $this->userManager->get($userId);
  1075. $usersGroups = $this->groupManager->getUserGroupIds($user);
  1076. if (!empty($usersGroups)) {
  1077. $remainingGroups = array_diff($usersGroups, $excludedGroups);
  1078. // if the user is only in groups which are disabled for sharing then
  1079. // sharing is also disabled for the user
  1080. if (empty($remainingGroups)) {
  1081. $this->sharingDisabledForUsersCache[$userId] = true;
  1082. return true;
  1083. }
  1084. }
  1085. }
  1086. $this->sharingDisabledForUsersCache[$userId] = false;
  1087. return false;
  1088. }
  1089. /**
  1090. * @inheritdoc
  1091. */
  1092. public function outgoingServer2ServerSharesAllowed() {
  1093. return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
  1094. }
  1095. }