Manager.php 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Share20;
  8. use OC\Files\Mount\MoveableMount;
  9. use OC\KnownUser\KnownUserService;
  10. use OC\Share20\Exception\ProviderException;
  11. use OCA\Files_Sharing\AppInfo\Application;
  12. use OCP\EventDispatcher\IEventDispatcher;
  13. use OCP\Files\File;
  14. use OCP\Files\Folder;
  15. use OCP\Files\IRootFolder;
  16. use OCP\Files\Mount\IMountManager;
  17. use OCP\Files\Node;
  18. use OCP\HintException;
  19. use OCP\IConfig;
  20. use OCP\IDateTimeZone;
  21. use OCP\IGroupManager;
  22. use OCP\IL10N;
  23. use OCP\IURLGenerator;
  24. use OCP\IUser;
  25. use OCP\IUserManager;
  26. use OCP\IUserSession;
  27. use OCP\L10N\IFactory;
  28. use OCP\Mail\IMailer;
  29. use OCP\Security\Events\ValidatePasswordPolicyEvent;
  30. use OCP\Security\IHasher;
  31. use OCP\Security\ISecureRandom;
  32. use OCP\Share;
  33. use OCP\Share\Events\BeforeShareDeletedEvent;
  34. use OCP\Share\Events\ShareAcceptedEvent;
  35. use OCP\Share\Events\ShareCreatedEvent;
  36. use OCP\Share\Events\ShareDeletedEvent;
  37. use OCP\Share\Events\ShareDeletedFromSelfEvent;
  38. use OCP\Share\Exceptions\AlreadySharedException;
  39. use OCP\Share\Exceptions\GenericShareException;
  40. use OCP\Share\Exceptions\ShareNotFound;
  41. use OCP\Share\IManager;
  42. use OCP\Share\IProviderFactory;
  43. use OCP\Share\IShare;
  44. use OCP\Share\IShareProvider;
  45. use Psr\Log\LoggerInterface;
  46. /**
  47. * This class is the communication hub for all sharing related operations.
  48. */
  49. class Manager implements IManager {
  50. private IL10N|null $l;
  51. private LegacyHooks $legacyHooks;
  52. public function __construct(
  53. private LoggerInterface $logger,
  54. private IConfig $config,
  55. private ISecureRandom $secureRandom,
  56. private IHasher $hasher,
  57. private IMountManager $mountManager,
  58. private IGroupManager $groupManager,
  59. private IFactory $l10nFactory,
  60. private IProviderFactory $factory,
  61. private IUserManager $userManager,
  62. private IRootFolder $rootFolder,
  63. private IMailer $mailer,
  64. private IURLGenerator $urlGenerator,
  65. private \OC_Defaults $defaults,
  66. private IEventDispatcher $dispatcher,
  67. private IUserSession $userSession,
  68. private KnownUserService $knownUserService,
  69. private ShareDisableChecker $shareDisableChecker,
  70. private IDateTimeZone $dateTimeZone
  71. ) {
  72. $this->l = $this->l10nFactory->get('lib');
  73. // The constructor of LegacyHooks registers the listeners of share events
  74. // do not remove if those are not properly migrated
  75. $this->legacyHooks = new LegacyHooks($this->dispatcher);
  76. }
  77. /**
  78. * Convert from a full share id to a tuple (providerId, shareId)
  79. *
  80. * @param string $id
  81. * @return string[]
  82. */
  83. private function splitFullId($id) {
  84. return explode(':', $id, 2);
  85. }
  86. /**
  87. * Verify if a password meets all requirements
  88. *
  89. * @param string $password
  90. * @throws \Exception
  91. */
  92. protected function verifyPassword($password) {
  93. if ($password === null) {
  94. // No password is set, check if this is allowed.
  95. if ($this->shareApiLinkEnforcePassword()) {
  96. throw new \InvalidArgumentException('Passwords are enforced for link and mail shares');
  97. }
  98. return;
  99. }
  100. // Let others verify the password
  101. try {
  102. $this->dispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
  103. } catch (HintException $e) {
  104. throw new \Exception($e->getHint());
  105. }
  106. }
  107. /**
  108. * Check for generic requirements before creating a share
  109. *
  110. * @param IShare $share
  111. * @throws \InvalidArgumentException
  112. * @throws GenericShareException
  113. *
  114. * @suppress PhanUndeclaredClassMethod
  115. */
  116. protected function generalCreateChecks(IShare $share, bool $isUpdate = false) {
  117. if ($share->getShareType() === IShare::TYPE_USER) {
  118. // We expect a valid user as sharedWith for user shares
  119. if (!$this->userManager->userExists($share->getSharedWith())) {
  120. throw new \InvalidArgumentException('SharedWith is not a valid user');
  121. }
  122. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  123. // We expect a valid group as sharedWith for group shares
  124. if (!$this->groupManager->groupExists($share->getSharedWith())) {
  125. throw new \InvalidArgumentException('SharedWith is not a valid group');
  126. }
  127. } elseif ($share->getShareType() === IShare::TYPE_LINK) {
  128. // No check for TYPE_EMAIL here as we have a recipient for them
  129. if ($share->getSharedWith() !== null) {
  130. throw new \InvalidArgumentException('SharedWith should be empty');
  131. }
  132. } elseif ($share->getShareType() === IShare::TYPE_EMAIL) {
  133. if ($share->getSharedWith() === null) {
  134. throw new \InvalidArgumentException('SharedWith should not be empty');
  135. }
  136. } elseif ($share->getShareType() === IShare::TYPE_REMOTE) {
  137. if ($share->getSharedWith() === null) {
  138. throw new \InvalidArgumentException('SharedWith should not be empty');
  139. }
  140. } elseif ($share->getShareType() === IShare::TYPE_REMOTE_GROUP) {
  141. if ($share->getSharedWith() === null) {
  142. throw new \InvalidArgumentException('SharedWith should not be empty');
  143. }
  144. } elseif ($share->getShareType() === IShare::TYPE_CIRCLE) {
  145. $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
  146. if ($circle === null) {
  147. throw new \InvalidArgumentException('SharedWith is not a valid circle');
  148. }
  149. } elseif ($share->getShareType() === IShare::TYPE_ROOM) {
  150. } elseif ($share->getShareType() === IShare::TYPE_DECK) {
  151. } elseif ($share->getShareType() === IShare::TYPE_SCIENCEMESH) {
  152. } else {
  153. // We cannot handle other types yet
  154. throw new \InvalidArgumentException('unknown share type');
  155. }
  156. // Verify the initiator of the share is set
  157. if ($share->getSharedBy() === null) {
  158. throw new \InvalidArgumentException('SharedBy should be set');
  159. }
  160. // Cannot share with yourself
  161. if ($share->getShareType() === IShare::TYPE_USER &&
  162. $share->getSharedWith() === $share->getSharedBy()) {
  163. throw new \InvalidArgumentException('Cannot share with yourself');
  164. }
  165. // The path should be set
  166. if ($share->getNode() === null) {
  167. throw new \InvalidArgumentException('Path should be set');
  168. }
  169. // And it should be a file or a folder
  170. if (!($share->getNode() instanceof \OCP\Files\File) &&
  171. !($share->getNode() instanceof \OCP\Files\Folder)) {
  172. throw new \InvalidArgumentException('Path should be either a file or a folder');
  173. }
  174. // And you cannot share your rootfolder
  175. if ($this->userManager->userExists($share->getSharedBy())) {
  176. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  177. } else {
  178. $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  179. }
  180. if ($userFolder->getId() === $share->getNode()->getId()) {
  181. throw new \InvalidArgumentException('You cannot share your root folder');
  182. }
  183. // Check if we actually have share permissions
  184. if (!$share->getNode()->isShareable()) {
  185. $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getName()]);
  186. throw new GenericShareException($message_t, $message_t, 404);
  187. }
  188. // Permissions should be set
  189. if ($share->getPermissions() === null) {
  190. throw new \InvalidArgumentException('A share requires permissions');
  191. }
  192. $permissions = 0;
  193. $nodesForUser = $userFolder->getById($share->getNodeId());
  194. foreach ($nodesForUser as $node) {
  195. if ($node->getInternalPath() === '' && !$node->getMountPoint() instanceof MoveableMount) {
  196. // for the root of non-movable mount, the permissions we see if limited by the mount itself,
  197. // so we instead use the "raw" permissions from the storage
  198. $permissions |= $node->getStorage()->getPermissions('');
  199. } else {
  200. $permissions |= $node->getPermissions();
  201. }
  202. }
  203. // Check that we do not share with more permissions than we have
  204. if ($share->getPermissions() & ~$permissions) {
  205. $path = $userFolder->getRelativePath($share->getNode()->getPath());
  206. $message_t = $this->l->t('Cannot increase permissions of %s', [$path]);
  207. throw new GenericShareException($message_t, $message_t, 404);
  208. }
  209. // Check that read permissions are always set
  210. // Link shares are allowed to have no read permissions to allow upload to hidden folders
  211. $noReadPermissionRequired = $share->getShareType() === IShare::TYPE_LINK
  212. || $share->getShareType() === IShare::TYPE_EMAIL;
  213. if (!$noReadPermissionRequired &&
  214. ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
  215. throw new \InvalidArgumentException('Shares need at least read permissions');
  216. }
  217. if ($share->getNode() instanceof \OCP\Files\File) {
  218. if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
  219. $message_t = $this->l->t('Files cannot be shared with delete permissions');
  220. throw new GenericShareException($message_t);
  221. }
  222. if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
  223. $message_t = $this->l->t('Files cannot be shared with create permissions');
  224. throw new GenericShareException($message_t);
  225. }
  226. }
  227. }
  228. /**
  229. * Validate if the expiration date fits the system settings
  230. *
  231. * @param IShare $share The share to validate the expiration date of
  232. * @return IShare The modified share object
  233. * @throws GenericShareException
  234. * @throws \InvalidArgumentException
  235. * @throws \Exception
  236. */
  237. protected function validateExpirationDateInternal(IShare $share) {
  238. $isRemote = $share->getShareType() === IShare::TYPE_REMOTE || $share->getShareType() === IShare::TYPE_REMOTE_GROUP;
  239. $expirationDate = $share->getExpirationDate();
  240. if ($isRemote) {
  241. $defaultExpireDate = $this->shareApiRemoteDefaultExpireDate();
  242. $defaultExpireDays = $this->shareApiRemoteDefaultExpireDays();
  243. $configProp = 'remote_defaultExpDays';
  244. $isEnforced = $this->shareApiRemoteDefaultExpireDateEnforced();
  245. } else {
  246. $defaultExpireDate = $this->shareApiInternalDefaultExpireDate();
  247. $defaultExpireDays = $this->shareApiInternalDefaultExpireDays();
  248. $configProp = 'internal_defaultExpDays';
  249. $isEnforced = $this->shareApiInternalDefaultExpireDateEnforced();
  250. }
  251. // If $expirationDate is falsy, noExpirationDate is true and expiration not enforced
  252. // Then skip expiration date validation as null is accepted
  253. if(!($share->getNoExpirationDate() && !$isEnforced)) {
  254. if ($expirationDate != null) {
  255. $expirationDate->setTimezone($this->dateTimeZone->getTimeZone());
  256. $expirationDate->setTime(0, 0, 0);
  257. $date = new \DateTime('now', $this->dateTimeZone->getTimeZone());
  258. $date->setTime(0, 0, 0);
  259. if ($date >= $expirationDate) {
  260. $message = $this->l->t('Expiration date is in the past');
  261. throw new GenericShareException($message, $message, 404);
  262. }
  263. }
  264. // If expiredate is empty set a default one if there is a default
  265. $fullId = null;
  266. try {
  267. $fullId = $share->getFullId();
  268. } catch (\UnexpectedValueException $e) {
  269. // This is a new share
  270. }
  271. if ($fullId === null && $expirationDate === null && $defaultExpireDate) {
  272. $expirationDate = new \DateTime('now', $this->dateTimeZone->getTimeZone());
  273. $expirationDate->setTime(0, 0, 0);
  274. $days = (int)$this->config->getAppValue('core', $configProp, (string)$defaultExpireDays);
  275. if ($days > $defaultExpireDays) {
  276. $days = $defaultExpireDays;
  277. }
  278. $expirationDate->add(new \DateInterval('P' . $days . 'D'));
  279. }
  280. // If we enforce the expiration date check that is does not exceed
  281. if ($isEnforced) {
  282. if (empty($expirationDate)) {
  283. throw new \InvalidArgumentException('Expiration date is enforced');
  284. }
  285. $date = new \DateTime('now', $this->dateTimeZone->getTimeZone());
  286. $date->setTime(0, 0, 0);
  287. $date->add(new \DateInterval('P' . $defaultExpireDays . 'D'));
  288. if ($date < $expirationDate) {
  289. $message = $this->l->n('Cannot set expiration date more than %n day in the future', 'Cannot set expiration date more than %n days in the future', $defaultExpireDays);
  290. throw new GenericShareException($message, $message, 404);
  291. }
  292. }
  293. }
  294. $accepted = true;
  295. $message = '';
  296. \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
  297. 'expirationDate' => &$expirationDate,
  298. 'accepted' => &$accepted,
  299. 'message' => &$message,
  300. 'passwordSet' => $share->getPassword() !== null,
  301. ]);
  302. if (!$accepted) {
  303. throw new \Exception($message);
  304. }
  305. $share->setExpirationDate($expirationDate);
  306. return $share;
  307. }
  308. /**
  309. * Validate if the expiration date fits the system settings
  310. *
  311. * @param IShare $share The share to validate the expiration date of
  312. * @return IShare The modified share object
  313. * @throws GenericShareException
  314. * @throws \InvalidArgumentException
  315. * @throws \Exception
  316. */
  317. protected function validateExpirationDateLink(IShare $share) {
  318. $expirationDate = $share->getExpirationDate();
  319. $isEnforced = $this->shareApiLinkDefaultExpireDateEnforced();
  320. // If $expirationDate is falsy, noExpirationDate is true and expiration not enforced
  321. // Then skip expiration date validation as null is accepted
  322. if(!($share->getNoExpirationDate() && !$isEnforced)) {
  323. if ($expirationDate !== null) {
  324. $expirationDate->setTimezone($this->dateTimeZone->getTimeZone());
  325. $expirationDate->setTime(0, 0, 0);
  326. $date = new \DateTime('now', $this->dateTimeZone->getTimeZone());
  327. $date->setTime(0, 0, 0);
  328. if ($date >= $expirationDate) {
  329. $message = $this->l->t('Expiration date is in the past');
  330. throw new GenericShareException($message, $message, 404);
  331. }
  332. }
  333. // If expiredate is empty set a default one if there is a default
  334. $fullId = null;
  335. try {
  336. $fullId = $share->getFullId();
  337. } catch (\UnexpectedValueException $e) {
  338. // This is a new share
  339. }
  340. if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
  341. $expirationDate = new \DateTime('now', $this->dateTimeZone->getTimeZone());
  342. $expirationDate->setTime(0, 0, 0);
  343. $days = (int)$this->config->getAppValue('core', 'link_defaultExpDays', (string)$this->shareApiLinkDefaultExpireDays());
  344. if ($days > $this->shareApiLinkDefaultExpireDays()) {
  345. $days = $this->shareApiLinkDefaultExpireDays();
  346. }
  347. $expirationDate->add(new \DateInterval('P' . $days . 'D'));
  348. }
  349. // If we enforce the expiration date check that is does not exceed
  350. if ($isEnforced) {
  351. if (empty($expirationDate)) {
  352. throw new \InvalidArgumentException('Expiration date is enforced');
  353. }
  354. $date = new \DateTime('now', $this->dateTimeZone->getTimeZone());
  355. $date->setTime(0, 0, 0);
  356. $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
  357. if ($date < $expirationDate) {
  358. $message = $this->l->n('Cannot set expiration date more than %n day in the future', 'Cannot set expiration date more than %n days in the future', $this->shareApiLinkDefaultExpireDays());
  359. throw new GenericShareException($message, $message, 404);
  360. }
  361. }
  362. }
  363. $accepted = true;
  364. $message = '';
  365. \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
  366. 'expirationDate' => &$expirationDate,
  367. 'accepted' => &$accepted,
  368. 'message' => &$message,
  369. 'passwordSet' => $share->getPassword() !== null,
  370. ]);
  371. if (!$accepted) {
  372. throw new \Exception($message);
  373. }
  374. if ($expirationDate instanceof \DateTime) {
  375. $expirationDate->setTimezone(new \DateTimeZone(date_default_timezone_get()));
  376. }
  377. $share->setExpirationDate($expirationDate);
  378. return $share;
  379. }
  380. /**
  381. * Check for pre share requirements for user shares
  382. *
  383. * @param IShare $share
  384. * @throws \Exception
  385. */
  386. protected function userCreateChecks(IShare $share) {
  387. // Check if we can share with group members only
  388. if ($this->shareWithGroupMembersOnly()) {
  389. $sharedBy = $this->userManager->get($share->getSharedBy());
  390. $sharedWith = $this->userManager->get($share->getSharedWith());
  391. // Verify we can share with this user
  392. $groups = array_intersect(
  393. $this->groupManager->getUserGroupIds($sharedBy),
  394. $this->groupManager->getUserGroupIds($sharedWith)
  395. );
  396. // optional excluded groups
  397. $excludedGroups = $this->shareWithGroupMembersOnlyExcludeGroupsList();
  398. $groups = array_diff($groups, $excludedGroups);
  399. if (empty($groups)) {
  400. $message_t = $this->l->t('Sharing is only allowed with group members');
  401. throw new \Exception($message_t);
  402. }
  403. }
  404. /*
  405. * TODO: Could be costly, fix
  406. *
  407. * Also this is not what we want in the future.. then we want to squash identical shares.
  408. */
  409. $provider = $this->factory->getProviderForType(IShare::TYPE_USER);
  410. $existingShares = $provider->getSharesByPath($share->getNode());
  411. foreach ($existingShares as $existingShare) {
  412. // Ignore if it is the same share
  413. try {
  414. if ($existingShare->getFullId() === $share->getFullId()) {
  415. continue;
  416. }
  417. } catch (\UnexpectedValueException $e) {
  418. //Shares are not identical
  419. }
  420. // Identical share already exists
  421. if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
  422. $message = $this->l->t('Sharing %s failed, because this item is already shared with the account %s', [$share->getNode()->getName(), $share->getSharedWithDisplayName()]);
  423. throw new AlreadySharedException($message, $existingShare);
  424. }
  425. // The share is already shared with this user via a group share
  426. if ($existingShare->getShareType() === IShare::TYPE_GROUP) {
  427. $group = $this->groupManager->get($existingShare->getSharedWith());
  428. if (!is_null($group)) {
  429. $user = $this->userManager->get($share->getSharedWith());
  430. if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
  431. $message = $this->l->t('Sharing %s failed, because this item is already shared with the account %s', [$share->getNode()->getName(), $share->getSharedWithDisplayName()]);
  432. throw new AlreadySharedException($message, $existingShare);
  433. }
  434. }
  435. }
  436. }
  437. }
  438. /**
  439. * Check for pre share requirements for group shares
  440. *
  441. * @param IShare $share
  442. * @throws \Exception
  443. */
  444. protected function groupCreateChecks(IShare $share) {
  445. // Verify group shares are allowed
  446. if (!$this->allowGroupSharing()) {
  447. throw new \Exception('Group sharing is now allowed');
  448. }
  449. // Verify if the user can share with this group
  450. if ($this->shareWithGroupMembersOnly()) {
  451. $sharedBy = $this->userManager->get($share->getSharedBy());
  452. $sharedWith = $this->groupManager->get($share->getSharedWith());
  453. // optional excluded groups
  454. $excludedGroups = $this->shareWithGroupMembersOnlyExcludeGroupsList();
  455. if (is_null($sharedWith) || in_array($share->getSharedWith(), $excludedGroups) || !$sharedWith->inGroup($sharedBy)) {
  456. throw new \Exception('Sharing is only allowed within your own groups');
  457. }
  458. }
  459. /*
  460. * TODO: Could be costly, fix
  461. *
  462. * Also this is not what we want in the future.. then we want to squash identical shares.
  463. */
  464. $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
  465. $existingShares = $provider->getSharesByPath($share->getNode());
  466. foreach ($existingShares as $existingShare) {
  467. try {
  468. if ($existingShare->getFullId() === $share->getFullId()) {
  469. continue;
  470. }
  471. } catch (\UnexpectedValueException $e) {
  472. //It is a new share so just continue
  473. }
  474. if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
  475. throw new AlreadySharedException('Path is already shared with this group', $existingShare);
  476. }
  477. }
  478. }
  479. /**
  480. * Check for pre share requirements for link shares
  481. *
  482. * @param IShare $share
  483. * @throws \Exception
  484. */
  485. protected function linkCreateChecks(IShare $share) {
  486. // Are link shares allowed?
  487. if (!$this->shareApiAllowLinks()) {
  488. throw new \Exception('Link sharing is not allowed');
  489. }
  490. // Check if public upload is allowed
  491. if ($share->getNodeType() === 'folder' && !$this->shareApiLinkAllowPublicUpload() &&
  492. ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
  493. throw new \InvalidArgumentException('Public upload is not allowed');
  494. }
  495. }
  496. /**
  497. * To make sure we don't get invisible link shares we set the parent
  498. * of a link if it is a reshare. This is a quick word around
  499. * until we can properly display multiple link shares in the UI
  500. *
  501. * See: https://github.com/owncloud/core/issues/22295
  502. *
  503. * FIXME: Remove once multiple link shares can be properly displayed
  504. *
  505. * @param IShare $share
  506. */
  507. protected function setLinkParent(IShare $share) {
  508. // No sense in checking if the method is not there.
  509. if (method_exists($share, 'setParent')) {
  510. $storage = $share->getNode()->getStorage();
  511. if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
  512. /** @var \OCA\Files_Sharing\SharedStorage $storage */
  513. $share->setParent($storage->getShareId());
  514. }
  515. }
  516. }
  517. /**
  518. * @param File|Folder $path
  519. */
  520. protected function pathCreateChecks($path) {
  521. // Make sure that we do not share a path that contains a shared mountpoint
  522. if ($path instanceof \OCP\Files\Folder) {
  523. $mounts = $this->mountManager->findIn($path->getPath());
  524. foreach ($mounts as $mount) {
  525. if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
  526. throw new \InvalidArgumentException('Path contains files shared with you');
  527. }
  528. }
  529. }
  530. }
  531. /**
  532. * Check if the user that is sharing can actually share
  533. *
  534. * @param IShare $share
  535. * @throws \Exception
  536. */
  537. protected function canShare(IShare $share) {
  538. if (!$this->shareApiEnabled()) {
  539. throw new \Exception('Sharing is disabled');
  540. }
  541. if ($this->sharingDisabledForUser($share->getSharedBy())) {
  542. throw new \Exception('Sharing is disabled for you');
  543. }
  544. }
  545. /**
  546. * Share a path
  547. *
  548. * @param IShare $share
  549. * @return IShare The share object
  550. * @throws \Exception
  551. *
  552. * TODO: handle link share permissions or check them
  553. */
  554. public function createShare(IShare $share) {
  555. $this->canShare($share);
  556. $this->generalCreateChecks($share);
  557. // Verify if there are any issues with the path
  558. $this->pathCreateChecks($share->getNode());
  559. /*
  560. * On creation of a share the owner is always the owner of the path
  561. * Except for mounted federated shares.
  562. */
  563. $storage = $share->getNode()->getStorage();
  564. if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
  565. $parent = $share->getNode()->getParent();
  566. while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
  567. $parent = $parent->getParent();
  568. }
  569. $share->setShareOwner($parent->getOwner()->getUID());
  570. } else {
  571. if ($share->getNode()->getOwner()) {
  572. $share->setShareOwner($share->getNode()->getOwner()->getUID());
  573. } else {
  574. $share->setShareOwner($share->getSharedBy());
  575. }
  576. }
  577. try {
  578. // Verify share type
  579. if ($share->getShareType() === IShare::TYPE_USER) {
  580. $this->userCreateChecks($share);
  581. // Verify the expiration date
  582. $share = $this->validateExpirationDateInternal($share);
  583. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  584. $this->groupCreateChecks($share);
  585. // Verify the expiration date
  586. $share = $this->validateExpirationDateInternal($share);
  587. } elseif ($share->getShareType() === IShare::TYPE_REMOTE || $share->getShareType() === IShare::TYPE_REMOTE_GROUP) {
  588. //Verify the expiration date
  589. $share = $this->validateExpirationDateInternal($share);
  590. } elseif ($share->getShareType() === IShare::TYPE_LINK
  591. || $share->getShareType() === IShare::TYPE_EMAIL) {
  592. $this->linkCreateChecks($share);
  593. $this->setLinkParent($share);
  594. // For now ignore a set token.
  595. $share->setToken(
  596. $this->secureRandom->generate(
  597. \OC\Share\Constants::TOKEN_LENGTH,
  598. \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
  599. )
  600. );
  601. // Verify the expiration date
  602. $share = $this->validateExpirationDateLink($share);
  603. // Verify the password
  604. $this->verifyPassword($share->getPassword());
  605. // If a password is set. Hash it!
  606. if ($share->getShareType() === IShare::TYPE_LINK
  607. && $share->getPassword() !== null) {
  608. $share->setPassword($this->hasher->hash($share->getPassword()));
  609. }
  610. }
  611. // Cannot share with the owner
  612. if ($share->getShareType() === IShare::TYPE_USER &&
  613. $share->getSharedWith() === $share->getShareOwner()) {
  614. throw new \InvalidArgumentException('Cannot share with the share owner');
  615. }
  616. // Generate the target
  617. $defaultShareFolder = $this->config->getSystemValue('share_folder', '/');
  618. $allowCustomShareFolder = $this->config->getSystemValueBool('sharing.allow_custom_share_folder', true);
  619. if ($allowCustomShareFolder) {
  620. $shareFolder = $this->config->getUserValue($share->getSharedWith(), Application::APP_ID, 'share_folder', $defaultShareFolder);
  621. } else {
  622. $shareFolder = $defaultShareFolder;
  623. }
  624. $target = $shareFolder . '/' . $share->getNode()->getName();
  625. $target = \OC\Files\Filesystem::normalizePath($target);
  626. $share->setTarget($target);
  627. // Pre share event
  628. $event = new Share\Events\BeforeShareCreatedEvent($share);
  629. $this->dispatcher->dispatchTyped($event);
  630. if ($event->isPropagationStopped() && $event->getError()) {
  631. throw new \Exception($event->getError());
  632. }
  633. $oldShare = $share;
  634. $provider = $this->factory->getProviderForType($share->getShareType());
  635. $share = $provider->create($share);
  636. // Reuse the node we already have
  637. $share->setNode($oldShare->getNode());
  638. // Reset the target if it is null for the new share
  639. if ($share->getTarget() === '') {
  640. $share->setTarget($target);
  641. }
  642. } catch (AlreadySharedException $e) {
  643. // if a share for the same target already exists, dont create a new one, but do trigger the hooks and notifications again
  644. $oldShare = $share;
  645. // Reuse the node we already have
  646. $share = $e->getExistingShare();
  647. $share->setNode($oldShare->getNode());
  648. }
  649. // Post share event
  650. $this->dispatcher->dispatchTyped(new ShareCreatedEvent($share));
  651. if ($this->config->getSystemValueBool('sharing.enable_share_mail', true)
  652. && $share->getShareType() === IShare::TYPE_USER) {
  653. $mailSend = $share->getMailSend();
  654. if ($mailSend === true) {
  655. $user = $this->userManager->get($share->getSharedWith());
  656. if ($user !== null) {
  657. $emailAddress = $user->getEMailAddress();
  658. if ($emailAddress !== null && $emailAddress !== '') {
  659. $userLang = $this->l10nFactory->getUserLanguage($user);
  660. $l = $this->l10nFactory->get('lib', $userLang);
  661. $this->sendMailNotification(
  662. $l,
  663. $share->getNode()->getName(),
  664. $this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]),
  665. $share->getSharedBy(),
  666. $emailAddress,
  667. $share->getExpirationDate(),
  668. $share->getNote()
  669. );
  670. $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
  671. } else {
  672. $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
  673. }
  674. } else {
  675. $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
  676. }
  677. } else {
  678. $this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
  679. }
  680. }
  681. return $share;
  682. }
  683. /**
  684. * Send mail notifications
  685. *
  686. * This method will catch and log mail transmission errors
  687. *
  688. * @param IL10N $l Language of the recipient
  689. * @param string $filename file/folder name
  690. * @param string $link link to the file/folder
  691. * @param string $initiator user ID of share sender
  692. * @param string $shareWith email address of share receiver
  693. * @param \DateTime|null $expiration
  694. */
  695. protected function sendMailNotification(IL10N $l,
  696. $filename,
  697. $link,
  698. $initiator,
  699. $shareWith,
  700. ?\DateTime $expiration = null,
  701. $note = '') {
  702. $initiatorUser = $this->userManager->get($initiator);
  703. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  704. $message = $this->mailer->createMessage();
  705. $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
  706. 'filename' => $filename,
  707. 'link' => $link,
  708. 'initiator' => $initiatorDisplayName,
  709. 'expiration' => $expiration,
  710. 'shareWith' => $shareWith,
  711. ]);
  712. $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]));
  713. $emailTemplate->addHeader();
  714. $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
  715. $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
  716. if ($note !== '') {
  717. $emailTemplate->addBodyText(htmlspecialchars($note), $note);
  718. }
  719. $emailTemplate->addBodyText(
  720. htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
  721. $text
  722. );
  723. $emailTemplate->addBodyButton(
  724. $l->t('Open »%s«', [$filename]),
  725. $link
  726. );
  727. $message->setTo([$shareWith]);
  728. // The "From" contains the sharers name
  729. $instanceName = $this->defaults->getName();
  730. $senderName = $l->t(
  731. '%1$s via %2$s',
  732. [
  733. $initiatorDisplayName,
  734. $instanceName,
  735. ]
  736. );
  737. $message->setFrom([\OCP\Util::getDefaultEmailAddress('noreply') => $senderName]);
  738. // The "Reply-To" is set to the sharer if an mail address is configured
  739. // also the default footer contains a "Do not reply" which needs to be adjusted.
  740. $initiatorEmail = $initiatorUser->getEMailAddress();
  741. if ($initiatorEmail !== null) {
  742. $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
  743. $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan($l->getLanguageCode()) !== '' ? ' - ' . $this->defaults->getSlogan($l->getLanguageCode()) : ''));
  744. } else {
  745. $emailTemplate->addFooter('', $l->getLanguageCode());
  746. }
  747. $message->useTemplate($emailTemplate);
  748. try {
  749. $failedRecipients = $this->mailer->send($message);
  750. if (!empty($failedRecipients)) {
  751. $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
  752. return;
  753. }
  754. } catch (\Exception $e) {
  755. $this->logger->error('Share notification mail could not be sent', ['exception' => $e]);
  756. }
  757. }
  758. /**
  759. * Update a share
  760. *
  761. * @param IShare $share
  762. * @return IShare The share object
  763. * @throws \InvalidArgumentException
  764. */
  765. public function updateShare(IShare $share) {
  766. $expirationDateUpdated = false;
  767. $this->canShare($share);
  768. try {
  769. $originalShare = $this->getShareById($share->getFullId());
  770. } catch (\UnexpectedValueException $e) {
  771. throw new \InvalidArgumentException('Share does not have a full id');
  772. }
  773. // We cannot change the share type!
  774. if ($share->getShareType() !== $originalShare->getShareType()) {
  775. throw new \InvalidArgumentException('Cannot change share type');
  776. }
  777. // We can only change the recipient on user shares
  778. if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
  779. $share->getShareType() !== IShare::TYPE_USER) {
  780. throw new \InvalidArgumentException('Can only update recipient on user shares');
  781. }
  782. // Cannot share with the owner
  783. if ($share->getShareType() === IShare::TYPE_USER &&
  784. $share->getSharedWith() === $share->getShareOwner()) {
  785. throw new \InvalidArgumentException('Cannot share with the share owner');
  786. }
  787. $this->generalCreateChecks($share, true);
  788. if ($share->getShareType() === IShare::TYPE_USER) {
  789. $this->userCreateChecks($share);
  790. if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
  791. //Verify the expiration date
  792. $this->validateExpirationDateInternal($share);
  793. $expirationDateUpdated = true;
  794. }
  795. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  796. $this->groupCreateChecks($share);
  797. if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
  798. //Verify the expiration date
  799. $this->validateExpirationDateInternal($share);
  800. $expirationDateUpdated = true;
  801. }
  802. } elseif ($share->getShareType() === IShare::TYPE_LINK
  803. || $share->getShareType() === IShare::TYPE_EMAIL) {
  804. $this->linkCreateChecks($share);
  805. // The new password is not set again if it is the same as the old
  806. // one, unless when switching from sending by Talk to sending by
  807. // mail.
  808. $plainTextPassword = $share->getPassword();
  809. $updatedPassword = $this->updateSharePasswordIfNeeded($share, $originalShare);
  810. /**
  811. * Cannot enable the getSendPasswordByTalk if there is no password set
  812. */
  813. if (empty($plainTextPassword) && $share->getSendPasswordByTalk()) {
  814. throw new \InvalidArgumentException('Cannot enable sending the password by Talk with an empty password');
  815. }
  816. /**
  817. * If we're in a mail share, we need to force a password change
  818. * as either the user is not aware of the password or is already (received by mail)
  819. * Thus the SendPasswordByTalk feature would not make sense
  820. */
  821. if (!$updatedPassword && $share->getShareType() === IShare::TYPE_EMAIL) {
  822. if (!$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
  823. throw new \InvalidArgumentException('Cannot enable sending the password by Talk without setting a new password');
  824. }
  825. if ($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk()) {
  826. throw new \InvalidArgumentException('Cannot disable sending the password by Talk without setting a new password');
  827. }
  828. }
  829. if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
  830. // Verify the expiration date
  831. $this->validateExpirationDateLink($share);
  832. $expirationDateUpdated = true;
  833. }
  834. } elseif ($share->getShareType() === IShare::TYPE_REMOTE || $share->getShareType() === IShare::TYPE_REMOTE_GROUP) {
  835. if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
  836. //Verify the expiration date
  837. $this->validateExpirationDateInternal($share);
  838. $expirationDateUpdated = true;
  839. }
  840. }
  841. $this->pathCreateChecks($share->getNode());
  842. // Now update the share!
  843. $provider = $this->factory->getProviderForType($share->getShareType());
  844. if ($share->getShareType() === IShare::TYPE_EMAIL) {
  845. $share = $provider->update($share, $plainTextPassword);
  846. } else {
  847. $share = $provider->update($share);
  848. }
  849. if ($expirationDateUpdated === true) {
  850. \OC_Hook::emit(Share::class, 'post_set_expiration_date', [
  851. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  852. 'itemSource' => $share->getNode()->getId(),
  853. 'date' => $share->getExpirationDate(),
  854. 'uidOwner' => $share->getSharedBy(),
  855. ]);
  856. }
  857. if ($share->getPassword() !== $originalShare->getPassword()) {
  858. \OC_Hook::emit(Share::class, 'post_update_password', [
  859. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  860. 'itemSource' => $share->getNode()->getId(),
  861. 'uidOwner' => $share->getSharedBy(),
  862. 'token' => $share->getToken(),
  863. 'disabled' => is_null($share->getPassword()),
  864. ]);
  865. }
  866. if ($share->getPermissions() !== $originalShare->getPermissions()) {
  867. if ($this->userManager->userExists($share->getShareOwner())) {
  868. $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  869. } else {
  870. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  871. }
  872. \OC_Hook::emit(Share::class, 'post_update_permissions', [
  873. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  874. 'itemSource' => $share->getNode()->getId(),
  875. 'shareType' => $share->getShareType(),
  876. 'shareWith' => $share->getSharedWith(),
  877. 'uidOwner' => $share->getSharedBy(),
  878. 'permissions' => $share->getPermissions(),
  879. 'attributes' => $share->getAttributes() !== null ? $share->getAttributes()->toArray() : null,
  880. 'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
  881. ]);
  882. }
  883. return $share;
  884. }
  885. /**
  886. * Accept a share.
  887. *
  888. * @param IShare $share
  889. * @param string $recipientId
  890. * @return IShare The share object
  891. * @throws \InvalidArgumentException
  892. * @since 9.0.0
  893. */
  894. public function acceptShare(IShare $share, string $recipientId): IShare {
  895. [$providerId,] = $this->splitFullId($share->getFullId());
  896. $provider = $this->factory->getProvider($providerId);
  897. if (!method_exists($provider, 'acceptShare')) {
  898. // TODO FIX ME
  899. throw new \InvalidArgumentException('Share provider does not support accepting');
  900. }
  901. $provider->acceptShare($share, $recipientId);
  902. $event = new ShareAcceptedEvent($share);
  903. $this->dispatcher->dispatchTyped($event);
  904. return $share;
  905. }
  906. /**
  907. * Updates the password of the given share if it is not the same as the
  908. * password of the original share.
  909. *
  910. * @param IShare $share the share to update its password.
  911. * @param IShare $originalShare the original share to compare its
  912. * password with.
  913. * @return boolean whether the password was updated or not.
  914. */
  915. private function updateSharePasswordIfNeeded(IShare $share, IShare $originalShare) {
  916. $passwordsAreDifferent = ($share->getPassword() !== $originalShare->getPassword()) &&
  917. (($share->getPassword() !== null && $originalShare->getPassword() === null) ||
  918. ($share->getPassword() === null && $originalShare->getPassword() !== null) ||
  919. ($share->getPassword() !== null && $originalShare->getPassword() !== null &&
  920. !$this->hasher->verify($share->getPassword(), $originalShare->getPassword())));
  921. // Password updated.
  922. if ($passwordsAreDifferent) {
  923. //Verify the password
  924. $this->verifyPassword($share->getPassword());
  925. // If a password is set. Hash it!
  926. if (!empty($share->getPassword())) {
  927. $share->setPassword($this->hasher->hash($share->getPassword()));
  928. if ($share->getShareType() === IShare::TYPE_EMAIL) {
  929. // Shares shared by email have temporary passwords
  930. $this->setSharePasswordExpirationTime($share);
  931. }
  932. return true;
  933. } else {
  934. // Empty string and null are seen as NOT password protected
  935. $share->setPassword(null);
  936. if ($share->getShareType() === IShare::TYPE_EMAIL) {
  937. $share->setPasswordExpirationTime(null);
  938. }
  939. return true;
  940. }
  941. } else {
  942. // Reset the password to the original one, as it is either the same
  943. // as the "new" password or a hashed version of it.
  944. $share->setPassword($originalShare->getPassword());
  945. }
  946. return false;
  947. }
  948. /**
  949. * Set the share's password expiration time
  950. */
  951. private function setSharePasswordExpirationTime(IShare $share): void {
  952. if (!$this->config->getSystemValueBool('sharing.enable_mail_link_password_expiration', false)) {
  953. // Sets password expiration date to NULL
  954. $share->setPasswordExpirationTime();
  955. return;
  956. }
  957. // Sets password expiration date
  958. $expirationTime = null;
  959. $now = new \DateTime();
  960. $expirationInterval = $this->config->getSystemValue('sharing.mail_link_password_expiration_interval', 3600);
  961. $expirationTime = $now->add(new \DateInterval('PT' . $expirationInterval . 'S'));
  962. $share->setPasswordExpirationTime($expirationTime);
  963. }
  964. /**
  965. * Delete all the children of this share
  966. * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
  967. *
  968. * @param IShare $share
  969. * @return IShare[] List of deleted shares
  970. */
  971. protected function deleteChildren(IShare $share) {
  972. $deletedShares = [];
  973. $provider = $this->factory->getProviderForType($share->getShareType());
  974. foreach ($provider->getChildren($share) as $child) {
  975. $this->dispatcher->dispatchTyped(new BeforeShareDeletedEvent($child));
  976. $deletedChildren = $this->deleteChildren($child);
  977. $deletedShares = array_merge($deletedShares, $deletedChildren);
  978. $provider->delete($child);
  979. $this->dispatcher->dispatchTyped(new ShareDeletedEvent($child));
  980. $deletedShares[] = $child;
  981. }
  982. return $deletedShares;
  983. }
  984. /**
  985. * Delete a share
  986. *
  987. * @param IShare $share
  988. * @throws ShareNotFound
  989. * @throws \InvalidArgumentException
  990. */
  991. public function deleteShare(IShare $share) {
  992. try {
  993. $share->getFullId();
  994. } catch (\UnexpectedValueException $e) {
  995. throw new \InvalidArgumentException('Share does not have a full id');
  996. }
  997. $this->dispatcher->dispatchTyped(new BeforeShareDeletedEvent($share));
  998. // Get all children and delete them as well
  999. $this->deleteChildren($share);
  1000. // Do the actual delete
  1001. $provider = $this->factory->getProviderForType($share->getShareType());
  1002. $provider->delete($share);
  1003. $this->dispatcher->dispatchTyped(new ShareDeletedEvent($share));
  1004. }
  1005. /**
  1006. * Unshare a file as the recipient.
  1007. * This can be different from a regular delete for example when one of
  1008. * the users in a groups deletes that share. But the provider should
  1009. * handle this.
  1010. *
  1011. * @param IShare $share
  1012. * @param string $recipientId
  1013. */
  1014. public function deleteFromSelf(IShare $share, $recipientId) {
  1015. [$providerId,] = $this->splitFullId($share->getFullId());
  1016. $provider = $this->factory->getProvider($providerId);
  1017. $provider->deleteFromSelf($share, $recipientId);
  1018. $event = new ShareDeletedFromSelfEvent($share);
  1019. $this->dispatcher->dispatchTyped($event);
  1020. }
  1021. public function restoreShare(IShare $share, string $recipientId): IShare {
  1022. [$providerId,] = $this->splitFullId($share->getFullId());
  1023. $provider = $this->factory->getProvider($providerId);
  1024. return $provider->restore($share, $recipientId);
  1025. }
  1026. /**
  1027. * @inheritdoc
  1028. */
  1029. public function moveShare(IShare $share, $recipientId) {
  1030. if ($share->getShareType() === IShare::TYPE_LINK
  1031. || $share->getShareType() === IShare::TYPE_EMAIL) {
  1032. throw new \InvalidArgumentException('Cannot change target of link share');
  1033. }
  1034. if ($share->getShareType() === IShare::TYPE_USER && $share->getSharedWith() !== $recipientId) {
  1035. throw new \InvalidArgumentException('Invalid recipient');
  1036. }
  1037. if ($share->getShareType() === IShare::TYPE_GROUP) {
  1038. $sharedWith = $this->groupManager->get($share->getSharedWith());
  1039. if (is_null($sharedWith)) {
  1040. throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
  1041. }
  1042. $recipient = $this->userManager->get($recipientId);
  1043. if (!$sharedWith->inGroup($recipient)) {
  1044. throw new \InvalidArgumentException('Invalid recipient');
  1045. }
  1046. }
  1047. [$providerId,] = $this->splitFullId($share->getFullId());
  1048. $provider = $this->factory->getProvider($providerId);
  1049. return $provider->move($share, $recipientId);
  1050. }
  1051. public function getSharesInFolder($userId, Folder $node, $reshares = false, $shallow = true) {
  1052. $providers = $this->factory->getAllProviders();
  1053. if (!$shallow) {
  1054. throw new \Exception("non-shallow getSharesInFolder is no longer supported");
  1055. }
  1056. return array_reduce($providers, function ($shares, IShareProvider $provider) use ($userId, $node, $reshares, $shallow) {
  1057. $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
  1058. foreach ($newShares as $fid => $data) {
  1059. if (!isset($shares[$fid])) {
  1060. $shares[$fid] = [];
  1061. }
  1062. $shares[$fid] = array_merge($shares[$fid], $data);
  1063. }
  1064. return $shares;
  1065. }, []);
  1066. }
  1067. /**
  1068. * @inheritdoc
  1069. */
  1070. public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
  1071. if ($path !== null &&
  1072. !($path instanceof \OCP\Files\File) &&
  1073. !($path instanceof \OCP\Files\Folder)) {
  1074. throw new \InvalidArgumentException('invalid path');
  1075. }
  1076. try {
  1077. $provider = $this->factory->getProviderForType($shareType);
  1078. } catch (ProviderException $e) {
  1079. return [];
  1080. }
  1081. $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
  1082. /*
  1083. * Work around so we don't return expired shares but still follow
  1084. * proper pagination.
  1085. */
  1086. $shares2 = [];
  1087. while (true) {
  1088. $added = 0;
  1089. foreach ($shares as $share) {
  1090. try {
  1091. $this->checkShare($share);
  1092. } catch (ShareNotFound $e) {
  1093. //Ignore since this basically means the share is deleted
  1094. continue;
  1095. }
  1096. $added++;
  1097. $shares2[] = $share;
  1098. if (count($shares2) === $limit) {
  1099. break;
  1100. }
  1101. }
  1102. // If we did not fetch more shares than the limit then there are no more shares
  1103. if (count($shares) < $limit) {
  1104. break;
  1105. }
  1106. if (count($shares2) === $limit) {
  1107. break;
  1108. }
  1109. // If there was no limit on the select we are done
  1110. if ($limit === -1) {
  1111. break;
  1112. }
  1113. $offset += $added;
  1114. // Fetch again $limit shares
  1115. $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
  1116. // No more shares means we are done
  1117. if (empty($shares)) {
  1118. break;
  1119. }
  1120. }
  1121. $shares = $shares2;
  1122. return $shares;
  1123. }
  1124. /**
  1125. * @inheritdoc
  1126. */
  1127. public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
  1128. try {
  1129. $provider = $this->factory->getProviderForType($shareType);
  1130. } catch (ProviderException $e) {
  1131. return [];
  1132. }
  1133. $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
  1134. // remove all shares which are already expired
  1135. foreach ($shares as $key => $share) {
  1136. try {
  1137. $this->checkShare($share);
  1138. } catch (ShareNotFound $e) {
  1139. unset($shares[$key]);
  1140. }
  1141. }
  1142. return $shares;
  1143. }
  1144. /**
  1145. * @inheritdoc
  1146. */
  1147. public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
  1148. $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
  1149. // Only get deleted shares
  1150. $shares = array_filter($shares, function (IShare $share) {
  1151. return $share->getPermissions() === 0;
  1152. });
  1153. // Only get shares where the owner still exists
  1154. $shares = array_filter($shares, function (IShare $share) {
  1155. return $this->userManager->userExists($share->getShareOwner());
  1156. });
  1157. return $shares;
  1158. }
  1159. /**
  1160. * @inheritdoc
  1161. */
  1162. public function getShareById($id, $recipient = null) {
  1163. if ($id === null) {
  1164. throw new ShareNotFound();
  1165. }
  1166. [$providerId, $id] = $this->splitFullId($id);
  1167. try {
  1168. $provider = $this->factory->getProvider($providerId);
  1169. } catch (ProviderException $e) {
  1170. throw new ShareNotFound();
  1171. }
  1172. $share = $provider->getShareById($id, $recipient);
  1173. $this->checkShare($share);
  1174. return $share;
  1175. }
  1176. /**
  1177. * Get all the shares for a given path
  1178. *
  1179. * @param \OCP\Files\Node $path
  1180. * @param int $page
  1181. * @param int $perPage
  1182. *
  1183. * @return Share[]
  1184. */
  1185. public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
  1186. return [];
  1187. }
  1188. /**
  1189. * Get the share by token possible with password
  1190. *
  1191. * @param string $token
  1192. * @return IShare
  1193. *
  1194. * @throws ShareNotFound
  1195. */
  1196. public function getShareByToken($token) {
  1197. // tokens cannot be valid local user names
  1198. if ($this->userManager->userExists($token)) {
  1199. throw new ShareNotFound();
  1200. }
  1201. $share = null;
  1202. try {
  1203. if ($this->shareApiAllowLinks()) {
  1204. $provider = $this->factory->getProviderForType(IShare::TYPE_LINK);
  1205. $share = $provider->getShareByToken($token);
  1206. }
  1207. } catch (ProviderException $e) {
  1208. } catch (ShareNotFound $e) {
  1209. }
  1210. // If it is not a link share try to fetch a federated share by token
  1211. if ($share === null) {
  1212. try {
  1213. $provider = $this->factory->getProviderForType(IShare::TYPE_REMOTE);
  1214. $share = $provider->getShareByToken($token);
  1215. } catch (ProviderException $e) {
  1216. } catch (ShareNotFound $e) {
  1217. }
  1218. }
  1219. // If it is not a link share try to fetch a mail share by token
  1220. if ($share === null && $this->shareProviderExists(IShare::TYPE_EMAIL)) {
  1221. try {
  1222. $provider = $this->factory->getProviderForType(IShare::TYPE_EMAIL);
  1223. $share = $provider->getShareByToken($token);
  1224. } catch (ProviderException $e) {
  1225. } catch (ShareNotFound $e) {
  1226. }
  1227. }
  1228. if ($share === null && $this->shareProviderExists(IShare::TYPE_CIRCLE)) {
  1229. try {
  1230. $provider = $this->factory->getProviderForType(IShare::TYPE_CIRCLE);
  1231. $share = $provider->getShareByToken($token);
  1232. } catch (ProviderException $e) {
  1233. } catch (ShareNotFound $e) {
  1234. }
  1235. }
  1236. if ($share === null && $this->shareProviderExists(IShare::TYPE_ROOM)) {
  1237. try {
  1238. $provider = $this->factory->getProviderForType(IShare::TYPE_ROOM);
  1239. $share = $provider->getShareByToken($token);
  1240. } catch (ProviderException $e) {
  1241. } catch (ShareNotFound $e) {
  1242. }
  1243. }
  1244. if ($share === null) {
  1245. throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
  1246. }
  1247. $this->checkShare($share);
  1248. /*
  1249. * Reduce the permissions for link or email shares if public upload is not enabled
  1250. */
  1251. if (($share->getShareType() === IShare::TYPE_LINK || $share->getShareType() === IShare::TYPE_EMAIL)
  1252. && $share->getNodeType() === 'folder' && !$this->shareApiLinkAllowPublicUpload()) {
  1253. $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
  1254. }
  1255. return $share;
  1256. }
  1257. /**
  1258. * Check expire date and disabled owner
  1259. *
  1260. * @throws ShareNotFound
  1261. */
  1262. protected function checkShare(IShare $share): void {
  1263. if ($share->isExpired()) {
  1264. $this->deleteShare($share);
  1265. throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
  1266. }
  1267. if ($this->config->getAppValue('files_sharing', 'hide_disabled_user_shares', 'no') === 'yes') {
  1268. $uids = array_unique([$share->getShareOwner(),$share->getSharedBy()]);
  1269. foreach ($uids as $uid) {
  1270. $user = $this->userManager->get($uid);
  1271. if ($user?->isEnabled() === false) {
  1272. throw new ShareNotFound($this->l->t('The requested share comes from a disabled user'));
  1273. }
  1274. }
  1275. }
  1276. }
  1277. /**
  1278. * Verify the password of a public share
  1279. *
  1280. * @param IShare $share
  1281. * @param ?string $password
  1282. * @return bool
  1283. */
  1284. public function checkPassword(IShare $share, $password) {
  1285. // if there is no password on the share object / passsword is null, there is nothing to check
  1286. if ($password === null || $share->getPassword() === null) {
  1287. return false;
  1288. }
  1289. // Makes sure password hasn't expired
  1290. $expirationTime = $share->getPasswordExpirationTime();
  1291. if ($expirationTime !== null && $expirationTime < new \DateTime()) {
  1292. return false;
  1293. }
  1294. $newHash = '';
  1295. if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
  1296. return false;
  1297. }
  1298. if (!empty($newHash)) {
  1299. $share->setPassword($newHash);
  1300. $provider = $this->factory->getProviderForType($share->getShareType());
  1301. $provider->update($share);
  1302. }
  1303. return true;
  1304. }
  1305. /**
  1306. * @inheritdoc
  1307. */
  1308. public function userDeleted($uid) {
  1309. $types = [IShare::TYPE_USER, IShare::TYPE_GROUP, IShare::TYPE_LINK, IShare::TYPE_REMOTE, IShare::TYPE_EMAIL];
  1310. foreach ($types as $type) {
  1311. try {
  1312. $provider = $this->factory->getProviderForType($type);
  1313. } catch (ProviderException $e) {
  1314. continue;
  1315. }
  1316. $provider->userDeleted($uid, $type);
  1317. }
  1318. }
  1319. /**
  1320. * @inheritdoc
  1321. */
  1322. public function groupDeleted($gid) {
  1323. $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
  1324. $provider->groupDeleted($gid);
  1325. $excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
  1326. if ($excludedGroups === '') {
  1327. return;
  1328. }
  1329. $excludedGroups = json_decode($excludedGroups, true);
  1330. if (json_last_error() !== JSON_ERROR_NONE) {
  1331. return;
  1332. }
  1333. $excludedGroups = array_diff($excludedGroups, [$gid]);
  1334. $this->config->setAppValue('core', 'shareapi_exclude_groups_list', json_encode($excludedGroups));
  1335. }
  1336. /**
  1337. * @inheritdoc
  1338. */
  1339. public function userDeletedFromGroup($uid, $gid) {
  1340. $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
  1341. $provider->userDeletedFromGroup($uid, $gid);
  1342. }
  1343. /**
  1344. * Get access list to a path. This means
  1345. * all the users that can access a given path.
  1346. *
  1347. * Consider:
  1348. * -root
  1349. * |-folder1 (23)
  1350. * |-folder2 (32)
  1351. * |-fileA (42)
  1352. *
  1353. * fileA is shared with user1 and user1@server1 and email1@maildomain1
  1354. * folder2 is shared with group2 (user4 is a member of group2)
  1355. * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
  1356. * and email2@maildomain2
  1357. *
  1358. * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
  1359. * [
  1360. * users => [
  1361. * 'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
  1362. * 'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
  1363. * 'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
  1364. * ],
  1365. * remote => [
  1366. * 'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
  1367. * 'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
  1368. * ],
  1369. * public => bool
  1370. * mail => [
  1371. * 'email1@maildomain1' => ['node_id' => 42, 'token' => 'aBcDeFg'],
  1372. * 'email2@maildomain2' => ['node_id' => 23, 'token' => 'hIjKlMn'],
  1373. * ]
  1374. * ]
  1375. *
  1376. * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
  1377. * [
  1378. * users => ['user1', 'user2', 'user4'],
  1379. * remote => bool,
  1380. * public => bool
  1381. * mail => ['email1@maildomain1', 'email2@maildomain2']
  1382. * ]
  1383. *
  1384. * This is required for encryption/activity
  1385. *
  1386. * @param \OCP\Files\Node $path
  1387. * @param bool $recursive Should we check all parent folders as well
  1388. * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
  1389. * @return array
  1390. */
  1391. public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
  1392. $owner = $path->getOwner();
  1393. if ($owner === null) {
  1394. return [];
  1395. }
  1396. $owner = $owner->getUID();
  1397. if ($currentAccess) {
  1398. $al = ['users' => [], 'remote' => [], 'public' => false, 'mail' => []];
  1399. } else {
  1400. $al = ['users' => [], 'remote' => false, 'public' => false, 'mail' => []];
  1401. }
  1402. if (!$this->userManager->userExists($owner)) {
  1403. return $al;
  1404. }
  1405. //Get node for the owner and correct the owner in case of external storage
  1406. $userFolder = $this->rootFolder->getUserFolder($owner);
  1407. if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
  1408. $path = $userFolder->getFirstNodeById($path->getId());
  1409. if ($path === null || $path->getOwner() === null) {
  1410. return [];
  1411. }
  1412. $owner = $path->getOwner()->getUID();
  1413. }
  1414. $providers = $this->factory->getAllProviders();
  1415. /** @var Node[] $nodes */
  1416. $nodes = [];
  1417. if ($currentAccess) {
  1418. $ownerPath = $path->getPath();
  1419. $ownerPath = explode('/', $ownerPath, 4);
  1420. if (count($ownerPath) < 4) {
  1421. $ownerPath = '';
  1422. } else {
  1423. $ownerPath = $ownerPath[3];
  1424. }
  1425. $al['users'][$owner] = [
  1426. 'node_id' => $path->getId(),
  1427. 'node_path' => '/' . $ownerPath,
  1428. ];
  1429. } else {
  1430. $al['users'][] = $owner;
  1431. }
  1432. // Collect all the shares
  1433. while ($path->getPath() !== $userFolder->getPath()) {
  1434. $nodes[] = $path;
  1435. if (!$recursive) {
  1436. break;
  1437. }
  1438. $path = $path->getParent();
  1439. }
  1440. foreach ($providers as $provider) {
  1441. $tmp = $provider->getAccessList($nodes, $currentAccess);
  1442. foreach ($tmp as $k => $v) {
  1443. if (isset($al[$k])) {
  1444. if (is_array($al[$k])) {
  1445. if ($currentAccess) {
  1446. $al[$k] += $v;
  1447. } else {
  1448. $al[$k] = array_merge($al[$k], $v);
  1449. $al[$k] = array_unique($al[$k]);
  1450. $al[$k] = array_values($al[$k]);
  1451. }
  1452. } else {
  1453. $al[$k] = $al[$k] || $v;
  1454. }
  1455. } else {
  1456. $al[$k] = $v;
  1457. }
  1458. }
  1459. }
  1460. return $al;
  1461. }
  1462. /**
  1463. * Create a new share
  1464. *
  1465. * @return IShare
  1466. */
  1467. public function newShare() {
  1468. return new \OC\Share20\Share($this->rootFolder, $this->userManager);
  1469. }
  1470. /**
  1471. * Is the share API enabled
  1472. *
  1473. * @return bool
  1474. */
  1475. public function shareApiEnabled() {
  1476. return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
  1477. }
  1478. /**
  1479. * Is public link sharing enabled
  1480. *
  1481. * @return bool
  1482. */
  1483. public function shareApiAllowLinks() {
  1484. if ($this->config->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
  1485. return false;
  1486. }
  1487. $user = $this->userSession->getUser();
  1488. if ($user) {
  1489. $excludedGroups = json_decode($this->config->getAppValue('core', 'shareapi_allow_links_exclude_groups', '[]'));
  1490. if ($excludedGroups) {
  1491. $userGroups = $this->groupManager->getUserGroupIds($user);
  1492. return !(bool)array_intersect($excludedGroups, $userGroups);
  1493. }
  1494. }
  1495. return true;
  1496. }
  1497. /**
  1498. * Is password on public link requires
  1499. *
  1500. * @param bool Check group membership exclusion
  1501. * @return bool
  1502. */
  1503. public function shareApiLinkEnforcePassword(bool $checkGroupMembership = true) {
  1504. $excludedGroups = $this->config->getAppValue('core', 'shareapi_enforce_links_password_excluded_groups', '');
  1505. if ($excludedGroups !== '' && $checkGroupMembership) {
  1506. $excludedGroups = json_decode($excludedGroups);
  1507. $user = $this->userSession->getUser();
  1508. if ($user) {
  1509. $userGroups = $this->groupManager->getUserGroupIds($user);
  1510. if ((bool)array_intersect($excludedGroups, $userGroups)) {
  1511. return false;
  1512. }
  1513. }
  1514. }
  1515. return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
  1516. }
  1517. /**
  1518. * Is default link expire date enabled
  1519. *
  1520. * @return bool
  1521. */
  1522. public function shareApiLinkDefaultExpireDate() {
  1523. return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
  1524. }
  1525. /**
  1526. * Is default link expire date enforced
  1527. *`
  1528. *
  1529. * @return bool
  1530. */
  1531. public function shareApiLinkDefaultExpireDateEnforced() {
  1532. return $this->shareApiLinkDefaultExpireDate() &&
  1533. $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
  1534. }
  1535. /**
  1536. * Number of default link expire days
  1537. *
  1538. * @return int
  1539. */
  1540. public function shareApiLinkDefaultExpireDays() {
  1541. return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
  1542. }
  1543. /**
  1544. * Is default internal expire date enabled
  1545. *
  1546. * @return bool
  1547. */
  1548. public function shareApiInternalDefaultExpireDate(): bool {
  1549. return $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
  1550. }
  1551. /**
  1552. * Is default remote expire date enabled
  1553. *
  1554. * @return bool
  1555. */
  1556. public function shareApiRemoteDefaultExpireDate(): bool {
  1557. return $this->config->getAppValue('core', 'shareapi_default_remote_expire_date', 'no') === 'yes';
  1558. }
  1559. /**
  1560. * Is default expire date enforced
  1561. *
  1562. * @return bool
  1563. */
  1564. public function shareApiInternalDefaultExpireDateEnforced(): bool {
  1565. return $this->shareApiInternalDefaultExpireDate() &&
  1566. $this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
  1567. }
  1568. /**
  1569. * Is default expire date enforced for remote shares
  1570. *
  1571. * @return bool
  1572. */
  1573. public function shareApiRemoteDefaultExpireDateEnforced(): bool {
  1574. return $this->shareApiRemoteDefaultExpireDate() &&
  1575. $this->config->getAppValue('core', 'shareapi_enforce_remote_expire_date', 'no') === 'yes';
  1576. }
  1577. /**
  1578. * Number of default expire days
  1579. *
  1580. * @return int
  1581. */
  1582. public function shareApiInternalDefaultExpireDays(): int {
  1583. return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
  1584. }
  1585. /**
  1586. * Number of default expire days for remote shares
  1587. *
  1588. * @return int
  1589. */
  1590. public function shareApiRemoteDefaultExpireDays(): int {
  1591. return (int)$this->config->getAppValue('core', 'shareapi_remote_expire_after_n_days', '7');
  1592. }
  1593. /**
  1594. * Allow public upload on link shares
  1595. *
  1596. * @return bool
  1597. */
  1598. public function shareApiLinkAllowPublicUpload() {
  1599. return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
  1600. }
  1601. /**
  1602. * check if user can only share with group members
  1603. *
  1604. * @return bool
  1605. */
  1606. public function shareWithGroupMembersOnly() {
  1607. return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
  1608. }
  1609. /**
  1610. * If shareWithGroupMembersOnly is enabled, return an optional
  1611. * list of groups that must be excluded from the principle of
  1612. * belonging to the same group.
  1613. *
  1614. * @return array
  1615. */
  1616. public function shareWithGroupMembersOnlyExcludeGroupsList() {
  1617. if (!$this->shareWithGroupMembersOnly()) {
  1618. return [];
  1619. }
  1620. $excludeGroups = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members_exclude_group_list', '');
  1621. return json_decode($excludeGroups, true) ?? [];
  1622. }
  1623. /**
  1624. * Check if users can share with groups
  1625. *
  1626. * @return bool
  1627. */
  1628. public function allowGroupSharing() {
  1629. return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
  1630. }
  1631. public function allowEnumeration(): bool {
  1632. return $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
  1633. }
  1634. public function limitEnumerationToGroups(): bool {
  1635. return $this->allowEnumeration() &&
  1636. $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
  1637. }
  1638. public function limitEnumerationToPhone(): bool {
  1639. return $this->allowEnumeration() &&
  1640. $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
  1641. }
  1642. public function allowEnumerationFullMatch(): bool {
  1643. return $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_full_match', 'yes') === 'yes';
  1644. }
  1645. public function matchEmail(): bool {
  1646. return $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_full_match_email', 'yes') === 'yes';
  1647. }
  1648. public function ignoreSecondDisplayName(): bool {
  1649. return $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_full_match_ignore_second_dn', 'no') === 'yes';
  1650. }
  1651. public function currentUserCanEnumerateTargetUser(?IUser $currentUser, IUser $targetUser): bool {
  1652. if ($this->allowEnumerationFullMatch()) {
  1653. return true;
  1654. }
  1655. if (!$this->allowEnumeration()) {
  1656. return false;
  1657. }
  1658. if (!$this->limitEnumerationToPhone() && !$this->limitEnumerationToGroups()) {
  1659. // Enumeration is enabled and not restricted: OK
  1660. return true;
  1661. }
  1662. if (!$currentUser instanceof IUser) {
  1663. // Enumeration restrictions require an account
  1664. return false;
  1665. }
  1666. // Enumeration is limited to phone match
  1667. if ($this->limitEnumerationToPhone() && $this->knownUserService->isKnownToUser($currentUser->getUID(), $targetUser->getUID())) {
  1668. return true;
  1669. }
  1670. // Enumeration is limited to groups
  1671. if ($this->limitEnumerationToGroups()) {
  1672. $currentUserGroupIds = $this->groupManager->getUserGroupIds($currentUser);
  1673. $targetUserGroupIds = $this->groupManager->getUserGroupIds($targetUser);
  1674. if (!empty(array_intersect($currentUserGroupIds, $targetUserGroupIds))) {
  1675. return true;
  1676. }
  1677. }
  1678. return false;
  1679. }
  1680. /**
  1681. * Copied from \OC_Util::isSharingDisabledForUser
  1682. *
  1683. * TODO: Deprecate function from OC_Util
  1684. *
  1685. * @param string $userId
  1686. * @return bool
  1687. */
  1688. public function sharingDisabledForUser($userId) {
  1689. return $this->shareDisableChecker->sharingDisabledForUser($userId);
  1690. }
  1691. /**
  1692. * @inheritdoc
  1693. */
  1694. public function outgoingServer2ServerSharesAllowed() {
  1695. return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
  1696. }
  1697. /**
  1698. * @inheritdoc
  1699. */
  1700. public function outgoingServer2ServerGroupSharesAllowed() {
  1701. return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
  1702. }
  1703. /**
  1704. * @inheritdoc
  1705. */
  1706. public function shareProviderExists($shareType) {
  1707. try {
  1708. $this->factory->getProviderForType($shareType);
  1709. } catch (ProviderException $e) {
  1710. return false;
  1711. }
  1712. return true;
  1713. }
  1714. public function registerShareProvider(string $shareProviderClass): void {
  1715. $this->factory->registerProvider($shareProviderClass);
  1716. }
  1717. public function getAllShares(): iterable {
  1718. $providers = $this->factory->getAllProviders();
  1719. foreach ($providers as $provider) {
  1720. yield from $provider->getAllShares();
  1721. }
  1722. }
  1723. }