1
0

Manager.php 65 KB

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