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.

Manager.php 50KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649
  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 Daniel Calviño Sánchez <danxuliu@gmail.com>
  9. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Julius Härtl <jus@bitgrid.net>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Maxence Lange <maxence@artificial-owl.com>
  14. * @author Maxence Lange <maxence@nextcloud.com>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Pauli Järvinen <pauli.jarvinen@gmail.com>
  17. * @author Robin Appelman <robin@icewind.nl>
  18. * @author Roeland Jago Douma <roeland@famdouma.nl>
  19. * @author Stephan Müller <mail@stephanmueller.eu>
  20. * @author Vincent Petry <pvince81@owncloud.com>
  21. *
  22. * @license AGPL-3.0
  23. *
  24. * This code is free software: you can redistribute it and/or modify
  25. * it under the terms of the GNU Affero General Public License, version 3,
  26. * as published by the Free Software Foundation.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU Affero General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Affero General Public License, version 3,
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>
  35. *
  36. */
  37. namespace OC\Share20;
  38. use OC\Cache\CappedMemoryCache;
  39. use OC\Files\Mount\MoveableMount;
  40. use OC\HintException;
  41. use OC\Share20\Exception\ProviderException;
  42. use OCP\Files\File;
  43. use OCP\Files\Folder;
  44. use OCP\Files\IRootFolder;
  45. use OCP\Files\Mount\IMountManager;
  46. use OCP\Files\Node;
  47. use OCP\IConfig;
  48. use OCP\IGroupManager;
  49. use OCP\IL10N;
  50. use OCP\ILogger;
  51. use OCP\IURLGenerator;
  52. use OCP\IUser;
  53. use OCP\IUserManager;
  54. use OCP\L10N\IFactory;
  55. use OCP\Mail\IMailer;
  56. use OCP\Security\IHasher;
  57. use OCP\Security\ISecureRandom;
  58. use OCP\Share\Exceptions\GenericShareException;
  59. use OCP\Share\Exceptions\ShareNotFound;
  60. use OCP\Share\IManager;
  61. use OCP\Share\IProviderFactory;
  62. use OCP\Share\IShare;
  63. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  64. use Symfony\Component\EventDispatcher\GenericEvent;
  65. use OCP\Share\IShareProvider;
  66. use OCP\Share;
  67. /**
  68. * This class is the communication hub for all sharing related operations.
  69. */
  70. class Manager implements IManager {
  71. /** @var IProviderFactory */
  72. private $factory;
  73. /** @var ILogger */
  74. private $logger;
  75. /** @var IConfig */
  76. private $config;
  77. /** @var ISecureRandom */
  78. private $secureRandom;
  79. /** @var IHasher */
  80. private $hasher;
  81. /** @var IMountManager */
  82. private $mountManager;
  83. /** @var IGroupManager */
  84. private $groupManager;
  85. /** @var IL10N */
  86. private $l;
  87. /** @var IFactory */
  88. private $l10nFactory;
  89. /** @var IUserManager */
  90. private $userManager;
  91. /** @var IRootFolder */
  92. private $rootFolder;
  93. /** @var CappedMemoryCache */
  94. private $sharingDisabledForUsersCache;
  95. /** @var EventDispatcherInterface */
  96. private $eventDispatcher;
  97. /** @var LegacyHooks */
  98. private $legacyHooks;
  99. /** @var IMailer */
  100. private $mailer;
  101. /** @var IURLGenerator */
  102. private $urlGenerator;
  103. /** @var \OC_Defaults */
  104. private $defaults;
  105. /**
  106. * Manager constructor.
  107. *
  108. * @param ILogger $logger
  109. * @param IConfig $config
  110. * @param ISecureRandom $secureRandom
  111. * @param IHasher $hasher
  112. * @param IMountManager $mountManager
  113. * @param IGroupManager $groupManager
  114. * @param IL10N $l
  115. * @param IFactory $l10nFactory
  116. * @param IProviderFactory $factory
  117. * @param IUserManager $userManager
  118. * @param IRootFolder $rootFolder
  119. * @param EventDispatcherInterface $eventDispatcher
  120. * @param IMailer $mailer
  121. * @param IURLGenerator $urlGenerator
  122. * @param \OC_Defaults $defaults
  123. */
  124. public function __construct(
  125. ILogger $logger,
  126. IConfig $config,
  127. ISecureRandom $secureRandom,
  128. IHasher $hasher,
  129. IMountManager $mountManager,
  130. IGroupManager $groupManager,
  131. IL10N $l,
  132. IFactory $l10nFactory,
  133. IProviderFactory $factory,
  134. IUserManager $userManager,
  135. IRootFolder $rootFolder,
  136. EventDispatcherInterface $eventDispatcher,
  137. IMailer $mailer,
  138. IURLGenerator $urlGenerator,
  139. \OC_Defaults $defaults
  140. ) {
  141. $this->logger = $logger;
  142. $this->config = $config;
  143. $this->secureRandom = $secureRandom;
  144. $this->hasher = $hasher;
  145. $this->mountManager = $mountManager;
  146. $this->groupManager = $groupManager;
  147. $this->l = $l;
  148. $this->l10nFactory = $l10nFactory;
  149. $this->factory = $factory;
  150. $this->userManager = $userManager;
  151. $this->rootFolder = $rootFolder;
  152. $this->eventDispatcher = $eventDispatcher;
  153. $this->sharingDisabledForUsersCache = new CappedMemoryCache();
  154. $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
  155. $this->mailer = $mailer;
  156. $this->urlGenerator = $urlGenerator;
  157. $this->defaults = $defaults;
  158. }
  159. /**
  160. * Convert from a full share id to a tuple (providerId, shareId)
  161. *
  162. * @param string $id
  163. * @return string[]
  164. */
  165. private function splitFullId($id) {
  166. return explode(':', $id, 2);
  167. }
  168. /**
  169. * Verify if a password meets all requirements
  170. *
  171. * @param string $password
  172. * @throws \Exception
  173. */
  174. protected function verifyPassword($password) {
  175. if ($password === null) {
  176. // No password is set, check if this is allowed.
  177. if ($this->shareApiLinkEnforcePassword()) {
  178. throw new \InvalidArgumentException('Passwords are enforced for link shares');
  179. }
  180. return;
  181. }
  182. // Let others verify the password
  183. try {
  184. $event = new GenericEvent($password);
  185. $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
  186. } catch (HintException $e) {
  187. throw new \Exception($e->getHint());
  188. }
  189. }
  190. /**
  191. * Check for generic requirements before creating a share
  192. *
  193. * @param \OCP\Share\IShare $share
  194. * @throws \InvalidArgumentException
  195. * @throws GenericShareException
  196. *
  197. * @suppress PhanUndeclaredClassMethod
  198. */
  199. protected function generalCreateChecks(\OCP\Share\IShare $share) {
  200. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
  201. // We expect a valid user as sharedWith for user shares
  202. if (!$this->userManager->userExists($share->getSharedWith())) {
  203. throw new \InvalidArgumentException('SharedWith is not a valid user');
  204. }
  205. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
  206. // We expect a valid group as sharedWith for group shares
  207. if (!$this->groupManager->groupExists($share->getSharedWith())) {
  208. throw new \InvalidArgumentException('SharedWith is not a valid group');
  209. }
  210. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
  211. if ($share->getSharedWith() !== null) {
  212. throw new \InvalidArgumentException('SharedWith should be empty');
  213. }
  214. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
  215. if ($share->getSharedWith() === null) {
  216. throw new \InvalidArgumentException('SharedWith should not be empty');
  217. }
  218. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
  219. if ($share->getSharedWith() === null) {
  220. throw new \InvalidArgumentException('SharedWith should not be empty');
  221. }
  222. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
  223. if ($share->getSharedWith() === null) {
  224. throw new \InvalidArgumentException('SharedWith should not be empty');
  225. }
  226. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
  227. $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
  228. if ($circle === null) {
  229. throw new \InvalidArgumentException('SharedWith is not a valid circle');
  230. }
  231. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_ROOM) {
  232. } else {
  233. // We can't handle other types yet
  234. throw new \InvalidArgumentException('unknown share type');
  235. }
  236. // Verify the initiator of the share is set
  237. if ($share->getSharedBy() === null) {
  238. throw new \InvalidArgumentException('SharedBy should be set');
  239. }
  240. // Cannot share with yourself
  241. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
  242. $share->getSharedWith() === $share->getSharedBy()) {
  243. throw new \InvalidArgumentException('Can’t share with yourself');
  244. }
  245. // The path should be set
  246. if ($share->getNode() === null) {
  247. throw new \InvalidArgumentException('Path should be set');
  248. }
  249. // And it should be a file or a folder
  250. if (!($share->getNode() instanceof \OCP\Files\File) &&
  251. !($share->getNode() instanceof \OCP\Files\Folder)) {
  252. throw new \InvalidArgumentException('Path should be either a file or a folder');
  253. }
  254. // And you can't share your rootfolder
  255. if ($this->userManager->userExists($share->getSharedBy())) {
  256. $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
  257. } else {
  258. $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
  259. }
  260. if ($sharedPath === $share->getNode()->getPath()) {
  261. throw new \InvalidArgumentException('You can’t share your root folder');
  262. }
  263. // Check if we actually have share permissions
  264. if (!$share->getNode()->isShareable()) {
  265. $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
  266. throw new GenericShareException($message_t, $message_t, 404);
  267. }
  268. // Permissions should be set
  269. if ($share->getPermissions() === null) {
  270. throw new \InvalidArgumentException('A share requires permissions');
  271. }
  272. /*
  273. * Quick fix for #23536
  274. * Non moveable mount points do not have update and delete permissions
  275. * while we 'most likely' do have that on the storage.
  276. */
  277. $permissions = $share->getNode()->getPermissions();
  278. $mount = $share->getNode()->getMountPoint();
  279. if (!($mount instanceof MoveableMount)) {
  280. $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
  281. }
  282. // Check that we do not share with more permissions than we have
  283. if ($share->getPermissions() & ~$permissions) {
  284. $message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
  285. throw new GenericShareException($message_t, $message_t, 404);
  286. }
  287. // Check that read permissions are always set
  288. // Link shares are allowed to have no read permissions to allow upload to hidden folders
  289. $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
  290. || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
  291. if (!$noReadPermissionRequired &&
  292. ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
  293. throw new \InvalidArgumentException('Shares need at least read permissions');
  294. }
  295. if ($share->getNode() instanceof \OCP\Files\File) {
  296. if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
  297. $message_t = $this->l->t('Files can’t be shared with delete permissions');
  298. throw new GenericShareException($message_t);
  299. }
  300. if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
  301. $message_t = $this->l->t('Files can’t be shared with create permissions');
  302. throw new GenericShareException($message_t);
  303. }
  304. }
  305. }
  306. /**
  307. * Validate if the expiration date fits the system settings
  308. *
  309. * @param \OCP\Share\IShare $share The share to validate the expiration date of
  310. * @return \OCP\Share\IShare The modified share object
  311. * @throws GenericShareException
  312. * @throws \InvalidArgumentException
  313. * @throws \Exception
  314. */
  315. protected function validateExpirationDate(\OCP\Share\IShare $share) {
  316. $expirationDate = $share->getExpirationDate();
  317. if ($expirationDate !== null) {
  318. //Make sure the expiration date is a date
  319. $expirationDate->setTime(0, 0, 0);
  320. $date = new \DateTime();
  321. $date->setTime(0, 0, 0);
  322. if ($date >= $expirationDate) {
  323. $message = $this->l->t('Expiration date is in the past');
  324. throw new GenericShareException($message, $message, 404);
  325. }
  326. }
  327. // If expiredate is empty set a default one if there is a default
  328. $fullId = null;
  329. try {
  330. $fullId = $share->getFullId();
  331. } catch (\UnexpectedValueException $e) {
  332. // This is a new share
  333. }
  334. if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
  335. $expirationDate = new \DateTime();
  336. $expirationDate->setTime(0,0,0);
  337. $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
  338. }
  339. // If we enforce the expiration date check that is does not exceed
  340. if ($this->shareApiLinkDefaultExpireDateEnforced()) {
  341. if ($expirationDate === null) {
  342. throw new \InvalidArgumentException('Expiration date is enforced');
  343. }
  344. $date = new \DateTime();
  345. $date->setTime(0, 0, 0);
  346. $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
  347. if ($date < $expirationDate) {
  348. $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
  349. throw new GenericShareException($message, $message, 404);
  350. }
  351. }
  352. $accepted = true;
  353. $message = '';
  354. \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
  355. 'expirationDate' => &$expirationDate,
  356. 'accepted' => &$accepted,
  357. 'message' => &$message,
  358. 'passwordSet' => $share->getPassword() !== null,
  359. ]);
  360. if (!$accepted) {
  361. throw new \Exception($message);
  362. }
  363. $share->setExpirationDate($expirationDate);
  364. return $share;
  365. }
  366. /**
  367. * Check for pre share requirements for user shares
  368. *
  369. * @param \OCP\Share\IShare $share
  370. * @throws \Exception
  371. */
  372. protected function userCreateChecks(\OCP\Share\IShare $share) {
  373. // Check if we can share with group members only
  374. if ($this->shareWithGroupMembersOnly()) {
  375. $sharedBy = $this->userManager->get($share->getSharedBy());
  376. $sharedWith = $this->userManager->get($share->getSharedWith());
  377. // Verify we can share with this user
  378. $groups = array_intersect(
  379. $this->groupManager->getUserGroupIds($sharedBy),
  380. $this->groupManager->getUserGroupIds($sharedWith)
  381. );
  382. if (empty($groups)) {
  383. throw new \Exception('Sharing is only allowed with group members');
  384. }
  385. }
  386. /*
  387. * TODO: Could be costly, fix
  388. *
  389. * Also this is not what we want in the future.. then we want to squash identical shares.
  390. */
  391. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
  392. $existingShares = $provider->getSharesByPath($share->getNode());
  393. foreach($existingShares as $existingShare) {
  394. // Ignore if it is the same share
  395. try {
  396. if ($existingShare->getFullId() === $share->getFullId()) {
  397. continue;
  398. }
  399. } catch (\UnexpectedValueException $e) {
  400. //Shares are not identical
  401. }
  402. // Identical share already existst
  403. if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
  404. throw new \Exception('Path is already shared with this user');
  405. }
  406. // The share is already shared with this user via a group share
  407. if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
  408. $group = $this->groupManager->get($existingShare->getSharedWith());
  409. if (!is_null($group)) {
  410. $user = $this->userManager->get($share->getSharedWith());
  411. if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
  412. throw new \Exception('Path is already shared with this user');
  413. }
  414. }
  415. }
  416. }
  417. }
  418. /**
  419. * Check for pre share requirements for group shares
  420. *
  421. * @param \OCP\Share\IShare $share
  422. * @throws \Exception
  423. */
  424. protected function groupCreateChecks(\OCP\Share\IShare $share) {
  425. // Verify group shares are allowed
  426. if (!$this->allowGroupSharing()) {
  427. throw new \Exception('Group sharing is now allowed');
  428. }
  429. // Verify if the user can share with this group
  430. if ($this->shareWithGroupMembersOnly()) {
  431. $sharedBy = $this->userManager->get($share->getSharedBy());
  432. $sharedWith = $this->groupManager->get($share->getSharedWith());
  433. if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
  434. throw new \Exception('Sharing is only allowed within your own groups');
  435. }
  436. }
  437. /*
  438. * TODO: Could be costly, fix
  439. *
  440. * Also this is not what we want in the future.. then we want to squash identical shares.
  441. */
  442. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
  443. $existingShares = $provider->getSharesByPath($share->getNode());
  444. foreach($existingShares as $existingShare) {
  445. try {
  446. if ($existingShare->getFullId() === $share->getFullId()) {
  447. continue;
  448. }
  449. } catch (\UnexpectedValueException $e) {
  450. //It is a new share so just continue
  451. }
  452. if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
  453. throw new \Exception('Path is already shared with this group');
  454. }
  455. }
  456. }
  457. /**
  458. * Check for pre share requirements for link shares
  459. *
  460. * @param \OCP\Share\IShare $share
  461. * @throws \Exception
  462. */
  463. protected function linkCreateChecks(\OCP\Share\IShare $share) {
  464. // Are link shares allowed?
  465. if (!$this->shareApiAllowLinks()) {
  466. throw new \Exception('Link sharing is not allowed');
  467. }
  468. // Link shares by definition can't have share permissions
  469. if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
  470. throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
  471. }
  472. // Check if public upload is allowed
  473. if (!$this->shareApiLinkAllowPublicUpload() &&
  474. ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
  475. throw new \InvalidArgumentException('Public upload is not allowed');
  476. }
  477. }
  478. /**
  479. * To make sure we don't get invisible link shares we set the parent
  480. * of a link if it is a reshare. This is a quick word around
  481. * until we can properly display multiple link shares in the UI
  482. *
  483. * See: https://github.com/owncloud/core/issues/22295
  484. *
  485. * FIXME: Remove once multiple link shares can be properly displayed
  486. *
  487. * @param \OCP\Share\IShare $share
  488. */
  489. protected function setLinkParent(\OCP\Share\IShare $share) {
  490. // No sense in checking if the method is not there.
  491. if (method_exists($share, 'setParent')) {
  492. $storage = $share->getNode()->getStorage();
  493. if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
  494. /** @var \OCA\Files_Sharing\SharedStorage $storage */
  495. $share->setParent($storage->getShareId());
  496. }
  497. }
  498. }
  499. /**
  500. * @param File|Folder $path
  501. */
  502. protected function pathCreateChecks($path) {
  503. // Make sure that we do not share a path that contains a shared mountpoint
  504. if ($path instanceof \OCP\Files\Folder) {
  505. $mounts = $this->mountManager->findIn($path->getPath());
  506. foreach($mounts as $mount) {
  507. if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
  508. throw new \InvalidArgumentException('Path contains files shared with you');
  509. }
  510. }
  511. }
  512. }
  513. /**
  514. * Check if the user that is sharing can actually share
  515. *
  516. * @param \OCP\Share\IShare $share
  517. * @throws \Exception
  518. */
  519. protected function canShare(\OCP\Share\IShare $share) {
  520. if (!$this->shareApiEnabled()) {
  521. throw new \Exception('Sharing is disabled');
  522. }
  523. if ($this->sharingDisabledForUser($share->getSharedBy())) {
  524. throw new \Exception('Sharing is disabled for you');
  525. }
  526. }
  527. /**
  528. * Share a path
  529. *
  530. * @param \OCP\Share\IShare $share
  531. * @return Share The share object
  532. * @throws \Exception
  533. *
  534. * TODO: handle link share permissions or check them
  535. */
  536. public function createShare(\OCP\Share\IShare $share) {
  537. $this->canShare($share);
  538. $this->generalCreateChecks($share);
  539. // Verify if there are any issues with the path
  540. $this->pathCreateChecks($share->getNode());
  541. /*
  542. * On creation of a share the owner is always the owner of the path
  543. * Except for mounted federated shares.
  544. */
  545. $storage = $share->getNode()->getStorage();
  546. if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
  547. $parent = $share->getNode()->getParent();
  548. while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
  549. $parent = $parent->getParent();
  550. }
  551. $share->setShareOwner($parent->getOwner()->getUID());
  552. } else {
  553. $share->setShareOwner($share->getNode()->getOwner()->getUID());
  554. }
  555. //Verify share type
  556. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
  557. $this->userCreateChecks($share);
  558. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
  559. $this->groupCreateChecks($share);
  560. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
  561. $this->linkCreateChecks($share);
  562. $this->setLinkParent($share);
  563. /*
  564. * For now ignore a set token.
  565. */
  566. $share->setToken(
  567. $this->secureRandom->generate(
  568. \OC\Share\Constants::TOKEN_LENGTH,
  569. \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
  570. )
  571. );
  572. //Verify the expiration date
  573. $this->validateExpirationDate($share);
  574. //Verify the password
  575. $this->verifyPassword($share->getPassword());
  576. // If a password is set. Hash it!
  577. if ($share->getPassword() !== null) {
  578. $share->setPassword($this->hasher->hash($share->getPassword()));
  579. }
  580. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
  581. $share->setToken(
  582. $this->secureRandom->generate(
  583. \OC\Share\Constants::TOKEN_LENGTH,
  584. \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
  585. )
  586. );
  587. }
  588. // Cannot share with the owner
  589. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
  590. $share->getSharedWith() === $share->getShareOwner()) {
  591. throw new \InvalidArgumentException('Can’t share with the share owner');
  592. }
  593. // Generate the target
  594. $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
  595. $target = \OC\Files\Filesystem::normalizePath($target);
  596. $share->setTarget($target);
  597. // Pre share event
  598. $event = new GenericEvent($share);
  599. $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
  600. if ($event->isPropagationStopped() && $event->hasArgument('error')) {
  601. throw new \Exception($event->getArgument('error'));
  602. }
  603. $oldShare = $share;
  604. $provider = $this->factory->getProviderForType($share->getShareType());
  605. $share = $provider->create($share);
  606. //reuse the node we already have
  607. $share->setNode($oldShare->getNode());
  608. // Post share event
  609. $event = new GenericEvent($share);
  610. $this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
  611. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
  612. $mailSend = $share->getMailSend();
  613. if($mailSend === true) {
  614. $user = $this->userManager->get($share->getSharedWith());
  615. if ($user !== null) {
  616. $emailAddress = $user->getEMailAddress();
  617. if ($emailAddress !== null && $emailAddress !== '') {
  618. $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
  619. $l = $this->l10nFactory->get('lib', $userLang);
  620. $this->sendMailNotification(
  621. $l,
  622. $share->getNode()->getName(),
  623. $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
  624. $share->getSharedBy(),
  625. $emailAddress,
  626. $share->getExpirationDate()
  627. );
  628. $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
  629. } else {
  630. $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
  631. }
  632. } else {
  633. $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
  634. }
  635. } else {
  636. $this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
  637. }
  638. }
  639. return $share;
  640. }
  641. /**
  642. * Send mail notifications
  643. *
  644. * This method will catch and log mail transmission errors
  645. *
  646. * @param IL10N $l Language of the recipient
  647. * @param string $filename file/folder name
  648. * @param string $link link to the file/folder
  649. * @param string $initiator user ID of share sender
  650. * @param string $shareWith email address of share receiver
  651. * @param \DateTime|null $expiration
  652. */
  653. protected function sendMailNotification(IL10N $l,
  654. $filename,
  655. $link,
  656. $initiator,
  657. $shareWith,
  658. \DateTime $expiration = null) {
  659. $initiatorUser = $this->userManager->get($initiator);
  660. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  661. $message = $this->mailer->createMessage();
  662. $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
  663. 'filename' => $filename,
  664. 'link' => $link,
  665. 'initiator' => $initiatorDisplayName,
  666. 'expiration' => $expiration,
  667. 'shareWith' => $shareWith,
  668. ]);
  669. $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', array($initiatorDisplayName, $filename)));
  670. $emailTemplate->addHeader();
  671. $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
  672. $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
  673. $emailTemplate->addBodyText(
  674. htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
  675. $text
  676. );
  677. $emailTemplate->addBodyButton(
  678. $l->t('Open »%s«', [$filename]),
  679. $link
  680. );
  681. $message->setTo([$shareWith]);
  682. // The "From" contains the sharers name
  683. $instanceName = $this->defaults->getName();
  684. $senderName = $l->t(
  685. '%1$s via %2$s',
  686. [
  687. $initiatorDisplayName,
  688. $instanceName
  689. ]
  690. );
  691. $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
  692. // The "Reply-To" is set to the sharer if an mail address is configured
  693. // also the default footer contains a "Do not reply" which needs to be adjusted.
  694. $initiatorEmail = $initiatorUser->getEMailAddress();
  695. if($initiatorEmail !== null) {
  696. $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
  697. $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
  698. } else {
  699. $emailTemplate->addFooter();
  700. }
  701. $message->useTemplate($emailTemplate);
  702. try {
  703. $failedRecipients = $this->mailer->send($message);
  704. if(!empty($failedRecipients)) {
  705. $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
  706. return;
  707. }
  708. } catch (\Exception $e) {
  709. $this->logger->logException($e, ['message' => 'Share notification mail could not be sent']);
  710. }
  711. }
  712. /**
  713. * Update a share
  714. *
  715. * @param \OCP\Share\IShare $share
  716. * @return \OCP\Share\IShare The share object
  717. * @throws \InvalidArgumentException
  718. */
  719. public function updateShare(\OCP\Share\IShare $share) {
  720. $expirationDateUpdated = false;
  721. $this->canShare($share);
  722. try {
  723. $originalShare = $this->getShareById($share->getFullId());
  724. } catch (\UnexpectedValueException $e) {
  725. throw new \InvalidArgumentException('Share does not have a full id');
  726. }
  727. // We can't change the share type!
  728. if ($share->getShareType() !== $originalShare->getShareType()) {
  729. throw new \InvalidArgumentException('Can’t change share type');
  730. }
  731. // We can only change the recipient on user shares
  732. if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
  733. $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
  734. throw new \InvalidArgumentException('Can only update recipient on user shares');
  735. }
  736. // Cannot share with the owner
  737. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
  738. $share->getSharedWith() === $share->getShareOwner()) {
  739. throw new \InvalidArgumentException('Can’t share with the share owner');
  740. }
  741. $this->generalCreateChecks($share);
  742. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
  743. $this->userCreateChecks($share);
  744. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
  745. $this->groupCreateChecks($share);
  746. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
  747. $this->linkCreateChecks($share);
  748. $this->updateSharePasswordIfNeeded($share, $originalShare);
  749. if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
  750. //Verify the expiration date
  751. $this->validateExpirationDate($share);
  752. $expirationDateUpdated = true;
  753. }
  754. } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
  755. // The new password is not set again if it is the same as the old
  756. // one, unless when switching from sending by Talk to sending by
  757. // mail.
  758. $plainTextPassword = $share->getPassword();
  759. if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare) &&
  760. !($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk())) {
  761. $plainTextPassword = null;
  762. }
  763. if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
  764. // If the same password was already sent by mail the recipient
  765. // would already have access to the share without having to call
  766. // the sharer to verify her identity
  767. throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password');
  768. }
  769. }
  770. $this->pathCreateChecks($share->getNode());
  771. // Now update the share!
  772. $provider = $this->factory->getProviderForType($share->getShareType());
  773. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
  774. $share = $provider->update($share, $plainTextPassword);
  775. } else {
  776. $share = $provider->update($share);
  777. }
  778. if ($expirationDateUpdated === true) {
  779. \OC_Hook::emit(Share::class, 'post_set_expiration_date', [
  780. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  781. 'itemSource' => $share->getNode()->getId(),
  782. 'date' => $share->getExpirationDate(),
  783. 'uidOwner' => $share->getSharedBy(),
  784. ]);
  785. }
  786. if ($share->getPassword() !== $originalShare->getPassword()) {
  787. \OC_Hook::emit(Share::class, 'post_update_password', [
  788. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  789. 'itemSource' => $share->getNode()->getId(),
  790. 'uidOwner' => $share->getSharedBy(),
  791. 'token' => $share->getToken(),
  792. 'disabled' => is_null($share->getPassword()),
  793. ]);
  794. }
  795. if ($share->getPermissions() !== $originalShare->getPermissions()) {
  796. if ($this->userManager->userExists($share->getShareOwner())) {
  797. $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  798. } else {
  799. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  800. }
  801. \OC_Hook::emit(Share::class, 'post_update_permissions', array(
  802. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  803. 'itemSource' => $share->getNode()->getId(),
  804. 'shareType' => $share->getShareType(),
  805. 'shareWith' => $share->getSharedWith(),
  806. 'uidOwner' => $share->getSharedBy(),
  807. 'permissions' => $share->getPermissions(),
  808. 'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
  809. ));
  810. }
  811. return $share;
  812. }
  813. /**
  814. * Updates the password of the given share if it is not the same as the
  815. * password of the original share.
  816. *
  817. * @param \OCP\Share\IShare $share the share to update its password.
  818. * @param \OCP\Share\IShare $originalShare the original share to compare its
  819. * password with.
  820. * @return boolean whether the password was updated or not.
  821. */
  822. private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
  823. // Password updated.
  824. if ($share->getPassword() !== $originalShare->getPassword()) {
  825. //Verify the password
  826. $this->verifyPassword($share->getPassword());
  827. // If a password is set. Hash it!
  828. if ($share->getPassword() !== null) {
  829. $share->setPassword($this->hasher->hash($share->getPassword()));
  830. return true;
  831. }
  832. }
  833. return false;
  834. }
  835. /**
  836. * Delete all the children of this share
  837. * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
  838. *
  839. * @param \OCP\Share\IShare $share
  840. * @return \OCP\Share\IShare[] List of deleted shares
  841. */
  842. protected function deleteChildren(\OCP\Share\IShare $share) {
  843. $deletedShares = [];
  844. $provider = $this->factory->getProviderForType($share->getShareType());
  845. foreach ($provider->getChildren($share) as $child) {
  846. $deletedChildren = $this->deleteChildren($child);
  847. $deletedShares = array_merge($deletedShares, $deletedChildren);
  848. $provider->delete($child);
  849. $deletedShares[] = $child;
  850. }
  851. return $deletedShares;
  852. }
  853. /**
  854. * Delete a share
  855. *
  856. * @param \OCP\Share\IShare $share
  857. * @throws ShareNotFound
  858. * @throws \InvalidArgumentException
  859. */
  860. public function deleteShare(\OCP\Share\IShare $share) {
  861. try {
  862. $share->getFullId();
  863. } catch (\UnexpectedValueException $e) {
  864. throw new \InvalidArgumentException('Share does not have a full id');
  865. }
  866. $event = new GenericEvent($share);
  867. $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
  868. // Get all children and delete them as well
  869. $deletedShares = $this->deleteChildren($share);
  870. // Do the actual delete
  871. $provider = $this->factory->getProviderForType($share->getShareType());
  872. $provider->delete($share);
  873. // All the deleted shares caused by this delete
  874. $deletedShares[] = $share;
  875. // Emit post hook
  876. $event->setArgument('deletedShares', $deletedShares);
  877. $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
  878. }
  879. /**
  880. * Unshare a file as the recipient.
  881. * This can be different from a regular delete for example when one of
  882. * the users in a groups deletes that share. But the provider should
  883. * handle this.
  884. *
  885. * @param \OCP\Share\IShare $share
  886. * @param string $recipientId
  887. */
  888. public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
  889. list($providerId, ) = $this->splitFullId($share->getFullId());
  890. $provider = $this->factory->getProvider($providerId);
  891. $provider->deleteFromSelf($share, $recipientId);
  892. $event = new GenericEvent($share);
  893. $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
  894. }
  895. public function restoreShare(IShare $share, string $recipientId): IShare {
  896. list($providerId, ) = $this->splitFullId($share->getFullId());
  897. $provider = $this->factory->getProvider($providerId);
  898. return $provider->restore($share, $recipientId);
  899. }
  900. /**
  901. * @inheritdoc
  902. */
  903. public function moveShare(\OCP\Share\IShare $share, $recipientId) {
  904. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
  905. throw new \InvalidArgumentException('Can’t change target of link share');
  906. }
  907. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
  908. throw new \InvalidArgumentException('Invalid recipient');
  909. }
  910. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
  911. $sharedWith = $this->groupManager->get($share->getSharedWith());
  912. if (is_null($sharedWith)) {
  913. throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
  914. }
  915. $recipient = $this->userManager->get($recipientId);
  916. if (!$sharedWith->inGroup($recipient)) {
  917. throw new \InvalidArgumentException('Invalid recipient');
  918. }
  919. }
  920. list($providerId, ) = $this->splitFullId($share->getFullId());
  921. $provider = $this->factory->getProvider($providerId);
  922. $provider->move($share, $recipientId);
  923. }
  924. public function getSharesInFolder($userId, Folder $node, $reshares = false) {
  925. $providers = $this->factory->getAllProviders();
  926. return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
  927. $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
  928. foreach ($newShares as $fid => $data) {
  929. if (!isset($shares[$fid])) {
  930. $shares[$fid] = [];
  931. }
  932. $shares[$fid] = array_merge($shares[$fid], $data);
  933. }
  934. return $shares;
  935. }, []);
  936. }
  937. /**
  938. * @inheritdoc
  939. */
  940. public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
  941. if ($path !== null &&
  942. !($path instanceof \OCP\Files\File) &&
  943. !($path instanceof \OCP\Files\Folder)) {
  944. throw new \InvalidArgumentException('invalid path');
  945. }
  946. try {
  947. $provider = $this->factory->getProviderForType($shareType);
  948. } catch (ProviderException $e) {
  949. return [];
  950. }
  951. $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
  952. /*
  953. * Work around so we don't return expired shares but still follow
  954. * proper pagination.
  955. */
  956. $shares2 = [];
  957. while(true) {
  958. $added = 0;
  959. foreach ($shares as $share) {
  960. try {
  961. $this->checkExpireDate($share);
  962. } catch (ShareNotFound $e) {
  963. //Ignore since this basically means the share is deleted
  964. continue;
  965. }
  966. $added++;
  967. $shares2[] = $share;
  968. if (count($shares2) === $limit) {
  969. break;
  970. }
  971. }
  972. // If we did not fetch more shares than the limit then there are no more shares
  973. if (count($shares) < $limit) {
  974. break;
  975. }
  976. if (count($shares2) === $limit) {
  977. break;
  978. }
  979. // If there was no limit on the select we are done
  980. if ($limit === -1) {
  981. break;
  982. }
  983. $offset += $added;
  984. // Fetch again $limit shares
  985. $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
  986. // No more shares means we are done
  987. if (empty($shares)) {
  988. break;
  989. }
  990. }
  991. $shares = $shares2;
  992. return $shares;
  993. }
  994. /**
  995. * @inheritdoc
  996. */
  997. public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
  998. try {
  999. $provider = $this->factory->getProviderForType($shareType);
  1000. } catch (ProviderException $e) {
  1001. return [];
  1002. }
  1003. $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
  1004. // remove all shares which are already expired
  1005. foreach ($shares as $key => $share) {
  1006. try {
  1007. $this->checkExpireDate($share);
  1008. } catch (ShareNotFound $e) {
  1009. unset($shares[$key]);
  1010. }
  1011. }
  1012. return $shares;
  1013. }
  1014. /**
  1015. * @inheritdoc
  1016. */
  1017. public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
  1018. $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
  1019. // Only get deleted shares
  1020. $shares = array_filter($shares, function(IShare $share) {
  1021. return $share->getPermissions() === 0;
  1022. });
  1023. // Only get shares where the owner still exists
  1024. $shares = array_filter($shares, function (IShare $share) {
  1025. return $this->userManager->userExists($share->getShareOwner());
  1026. });
  1027. return $shares;
  1028. }
  1029. /**
  1030. * @inheritdoc
  1031. */
  1032. public function getShareById($id, $recipient = null) {
  1033. if ($id === null) {
  1034. throw new ShareNotFound();
  1035. }
  1036. list($providerId, $id) = $this->splitFullId($id);
  1037. try {
  1038. $provider = $this->factory->getProvider($providerId);
  1039. } catch (ProviderException $e) {
  1040. throw new ShareNotFound();
  1041. }
  1042. $share = $provider->getShareById($id, $recipient);
  1043. $this->checkExpireDate($share);
  1044. return $share;
  1045. }
  1046. /**
  1047. * Get all the shares for a given path
  1048. *
  1049. * @param \OCP\Files\Node $path
  1050. * @param int $page
  1051. * @param int $perPage
  1052. *
  1053. * @return Share[]
  1054. */
  1055. public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
  1056. return [];
  1057. }
  1058. /**
  1059. * Get the share by token possible with password
  1060. *
  1061. * @param string $token
  1062. * @return Share
  1063. *
  1064. * @throws ShareNotFound
  1065. */
  1066. public function getShareByToken($token) {
  1067. // tokens can't be valid local user names
  1068. if ($this->userManager->userExists($token)) {
  1069. throw new ShareNotFound();
  1070. }
  1071. $share = null;
  1072. try {
  1073. if($this->shareApiAllowLinks()) {
  1074. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
  1075. $share = $provider->getShareByToken($token);
  1076. }
  1077. } catch (ProviderException $e) {
  1078. } catch (ShareNotFound $e) {
  1079. }
  1080. // If it is not a link share try to fetch a federated share by token
  1081. if ($share === null) {
  1082. try {
  1083. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
  1084. $share = $provider->getShareByToken($token);
  1085. } catch (ProviderException $e) {
  1086. } catch (ShareNotFound $e) {
  1087. }
  1088. }
  1089. // If it is not a link share try to fetch a mail share by token
  1090. if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
  1091. try {
  1092. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
  1093. $share = $provider->getShareByToken($token);
  1094. } catch (ProviderException $e) {
  1095. } catch (ShareNotFound $e) {
  1096. }
  1097. }
  1098. if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
  1099. try {
  1100. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
  1101. $share = $provider->getShareByToken($token);
  1102. } catch (ProviderException $e) {
  1103. } catch (ShareNotFound $e) {
  1104. }
  1105. }
  1106. if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_ROOM)) {
  1107. try {
  1108. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_ROOM);
  1109. $share = $provider->getShareByToken($token);
  1110. } catch (ProviderException $e) {
  1111. } catch (ShareNotFound $e) {
  1112. }
  1113. }
  1114. if ($share === null) {
  1115. throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
  1116. }
  1117. $this->checkExpireDate($share);
  1118. /*
  1119. * Reduce the permissions for link shares if public upload is not enabled
  1120. */
  1121. if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
  1122. !$this->shareApiLinkAllowPublicUpload()) {
  1123. $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
  1124. }
  1125. return $share;
  1126. }
  1127. protected function checkExpireDate($share) {
  1128. if ($share->getExpirationDate() !== null &&
  1129. $share->getExpirationDate() <= new \DateTime()) {
  1130. $this->deleteShare($share);
  1131. throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
  1132. }
  1133. }
  1134. /**
  1135. * Verify the password of a public share
  1136. *
  1137. * @param \OCP\Share\IShare $share
  1138. * @param string $password
  1139. * @return bool
  1140. */
  1141. public function checkPassword(\OCP\Share\IShare $share, $password) {
  1142. $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
  1143. || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
  1144. if (!$passwordProtected) {
  1145. //TODO maybe exception?
  1146. return false;
  1147. }
  1148. if ($password === null || $share->getPassword() === null) {
  1149. return false;
  1150. }
  1151. $newHash = '';
  1152. if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
  1153. return false;
  1154. }
  1155. if (!empty($newHash)) {
  1156. $share->setPassword($newHash);
  1157. $provider = $this->factory->getProviderForType($share->getShareType());
  1158. $provider->update($share);
  1159. }
  1160. return true;
  1161. }
  1162. /**
  1163. * @inheritdoc
  1164. */
  1165. public function userDeleted($uid) {
  1166. $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
  1167. foreach ($types as $type) {
  1168. try {
  1169. $provider = $this->factory->getProviderForType($type);
  1170. } catch (ProviderException $e) {
  1171. continue;
  1172. }
  1173. $provider->userDeleted($uid, $type);
  1174. }
  1175. }
  1176. /**
  1177. * @inheritdoc
  1178. */
  1179. public function groupDeleted($gid) {
  1180. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
  1181. $provider->groupDeleted($gid);
  1182. }
  1183. /**
  1184. * @inheritdoc
  1185. */
  1186. public function userDeletedFromGroup($uid, $gid) {
  1187. $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
  1188. $provider->userDeletedFromGroup($uid, $gid);
  1189. }
  1190. /**
  1191. * Get access list to a path. This means
  1192. * all the users that can access a given path.
  1193. *
  1194. * Consider:
  1195. * -root
  1196. * |-folder1 (23)
  1197. * |-folder2 (32)
  1198. * |-fileA (42)
  1199. *
  1200. * fileA is shared with user1 and user1@server1
  1201. * folder2 is shared with group2 (user4 is a member of group2)
  1202. * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
  1203. *
  1204. * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
  1205. * [
  1206. * users => [
  1207. * 'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
  1208. * 'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
  1209. * 'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
  1210. * ],
  1211. * remote => [
  1212. * 'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
  1213. * 'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
  1214. * ],
  1215. * public => bool
  1216. * mail => bool
  1217. * ]
  1218. *
  1219. * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
  1220. * [
  1221. * users => ['user1', 'user2', 'user4'],
  1222. * remote => bool,
  1223. * public => bool
  1224. * mail => bool
  1225. * ]
  1226. *
  1227. * This is required for encryption/activity
  1228. *
  1229. * @param \OCP\Files\Node $path
  1230. * @param bool $recursive Should we check all parent folders as well
  1231. * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
  1232. * @return array
  1233. */
  1234. public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
  1235. $owner = $path->getOwner();
  1236. if ($owner === null) {
  1237. return [];
  1238. }
  1239. $owner = $owner->getUID();
  1240. if ($currentAccess) {
  1241. $al = ['users' => [], 'remote' => [], 'public' => false];
  1242. } else {
  1243. $al = ['users' => [], 'remote' => false, 'public' => false];
  1244. }
  1245. if (!$this->userManager->userExists($owner)) {
  1246. return $al;
  1247. }
  1248. //Get node for the owner and correct the owner in case of external storages
  1249. $userFolder = $this->rootFolder->getUserFolder($owner);
  1250. if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
  1251. $nodes = $userFolder->getById($path->getId());
  1252. $path = array_shift($nodes);
  1253. $owner = $path->getOwner()->getUID();
  1254. }
  1255. $providers = $this->factory->getAllProviders();
  1256. /** @var Node[] $nodes */
  1257. $nodes = [];
  1258. if ($currentAccess) {
  1259. $ownerPath = $path->getPath();
  1260. $ownerPath = explode('/', $ownerPath, 4);
  1261. if (count($ownerPath) < 4) {
  1262. $ownerPath = '';
  1263. } else {
  1264. $ownerPath = $ownerPath[3];
  1265. }
  1266. $al['users'][$owner] = [
  1267. 'node_id' => $path->getId(),
  1268. 'node_path' => '/' . $ownerPath,
  1269. ];
  1270. } else {
  1271. $al['users'][] = $owner;
  1272. }
  1273. // Collect all the shares
  1274. while ($path->getPath() !== $userFolder->getPath()) {
  1275. $nodes[] = $path;
  1276. if (!$recursive) {
  1277. break;
  1278. }
  1279. $path = $path->getParent();
  1280. }
  1281. foreach ($providers as $provider) {
  1282. $tmp = $provider->getAccessList($nodes, $currentAccess);
  1283. foreach ($tmp as $k => $v) {
  1284. if (isset($al[$k])) {
  1285. if (is_array($al[$k])) {
  1286. if ($currentAccess) {
  1287. $al[$k] += $v;
  1288. } else {
  1289. $al[$k] = array_merge($al[$k], $v);
  1290. $al[$k] = array_unique($al[$k]);
  1291. $al[$k] = array_values($al[$k]);
  1292. }
  1293. } else {
  1294. $al[$k] = $al[$k] || $v;
  1295. }
  1296. } else {
  1297. $al[$k] = $v;
  1298. }
  1299. }
  1300. }
  1301. return $al;
  1302. }
  1303. /**
  1304. * Create a new share
  1305. * @return \OCP\Share\IShare
  1306. */
  1307. public function newShare() {
  1308. return new \OC\Share20\Share($this->rootFolder, $this->userManager);
  1309. }
  1310. /**
  1311. * Is the share API enabled
  1312. *
  1313. * @return bool
  1314. */
  1315. public function shareApiEnabled() {
  1316. return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
  1317. }
  1318. /**
  1319. * Is public link sharing enabled
  1320. *
  1321. * @return bool
  1322. */
  1323. public function shareApiAllowLinks() {
  1324. return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
  1325. }
  1326. /**
  1327. * Is password on public link requires
  1328. *
  1329. * @return bool
  1330. */
  1331. public function shareApiLinkEnforcePassword() {
  1332. return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
  1333. }
  1334. /**
  1335. * Is default expire date enabled
  1336. *
  1337. * @return bool
  1338. */
  1339. public function shareApiLinkDefaultExpireDate() {
  1340. return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
  1341. }
  1342. /**
  1343. * Is default expire date enforced
  1344. *`
  1345. * @return bool
  1346. */
  1347. public function shareApiLinkDefaultExpireDateEnforced() {
  1348. return $this->shareApiLinkDefaultExpireDate() &&
  1349. $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
  1350. }
  1351. /**
  1352. * Number of default expire days
  1353. *shareApiLinkAllowPublicUpload
  1354. * @return int
  1355. */
  1356. public function shareApiLinkDefaultExpireDays() {
  1357. return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
  1358. }
  1359. /**
  1360. * Allow public upload on link shares
  1361. *
  1362. * @return bool
  1363. */
  1364. public function shareApiLinkAllowPublicUpload() {
  1365. return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
  1366. }
  1367. /**
  1368. * check if user can only share with group members
  1369. * @return bool
  1370. */
  1371. public function shareWithGroupMembersOnly() {
  1372. return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
  1373. }
  1374. /**
  1375. * Check if users can share with groups
  1376. * @return bool
  1377. */
  1378. public function allowGroupSharing() {
  1379. return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
  1380. }
  1381. /**
  1382. * Copied from \OC_Util::isSharingDisabledForUser
  1383. *
  1384. * TODO: Deprecate fuction from OC_Util
  1385. *
  1386. * @param string $userId
  1387. * @return bool
  1388. */
  1389. public function sharingDisabledForUser($userId) {
  1390. if ($userId === null) {
  1391. return false;
  1392. }
  1393. if (isset($this->sharingDisabledForUsersCache[$userId])) {
  1394. return $this->sharingDisabledForUsersCache[$userId];
  1395. }
  1396. if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
  1397. $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
  1398. $excludedGroups = json_decode($groupsList);
  1399. if (is_null($excludedGroups)) {
  1400. $excludedGroups = explode(',', $groupsList);
  1401. $newValue = json_encode($excludedGroups);
  1402. $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
  1403. }
  1404. $user = $this->userManager->get($userId);
  1405. $usersGroups = $this->groupManager->getUserGroupIds($user);
  1406. if (!empty($usersGroups)) {
  1407. $remainingGroups = array_diff($usersGroups, $excludedGroups);
  1408. // if the user is only in groups which are disabled for sharing then
  1409. // sharing is also disabled for the user
  1410. if (empty($remainingGroups)) {
  1411. $this->sharingDisabledForUsersCache[$userId] = true;
  1412. return true;
  1413. }
  1414. }
  1415. }
  1416. $this->sharingDisabledForUsersCache[$userId] = false;
  1417. return false;
  1418. }
  1419. /**
  1420. * @inheritdoc
  1421. */
  1422. public function outgoingServer2ServerSharesAllowed() {
  1423. return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
  1424. }
  1425. /**
  1426. * @inheritdoc
  1427. */
  1428. public function outgoingServer2ServerGroupSharesAllowed() {
  1429. return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
  1430. }
  1431. /**
  1432. * @inheritdoc
  1433. */
  1434. public function shareProviderExists($shareType) {
  1435. try {
  1436. $this->factory->getProviderForType($shareType);
  1437. } catch (ProviderException $e) {
  1438. return false;
  1439. }
  1440. return true;
  1441. }
  1442. }