Manager.php 63 KB

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