Manager.php 62 KB

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