1
0

Manager.php 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091
  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\Exceptions\AlreadySharedException;
  70. use OCP\Share\Exceptions\GenericShareException;
  71. use OCP\Share\Exceptions\ShareNotFound;
  72. use OCP\Share\IManager;
  73. use OCP\Share\IProviderFactory;
  74. use OCP\Share\IShare;
  75. use OCP\Share\IShareProvider;
  76. use Psr\Log\LoggerInterface;
  77. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  78. use Symfony\Component\EventDispatcher\GenericEvent;
  79. /**
  80. * This class is the communication hub for all sharing related operations.
  81. */
  82. class Manager implements IManager {
  83. /** @var IProviderFactory */
  84. private $factory;
  85. private LoggerInterface $logger;
  86. /** @var IConfig */
  87. private $config;
  88. /** @var ISecureRandom */
  89. private $secureRandom;
  90. /** @var IHasher */
  91. private $hasher;
  92. /** @var IMountManager */
  93. private $mountManager;
  94. /** @var IGroupManager */
  95. private $groupManager;
  96. /** @var IL10N */
  97. private $l;
  98. /** @var IFactory */
  99. private $l10nFactory;
  100. /** @var IUserManager */
  101. private $userManager;
  102. /** @var IRootFolder */
  103. private $rootFolder;
  104. /** @var CappedMemoryCache */
  105. private $sharingDisabledForUsersCache;
  106. /** @var EventDispatcherInterface */
  107. private $legacyDispatcher;
  108. /** @var LegacyHooks */
  109. private $legacyHooks;
  110. /** @var IMailer */
  111. private $mailer;
  112. /** @var IURLGenerator */
  113. private $urlGenerator;
  114. /** @var \OC_Defaults */
  115. private $defaults;
  116. /** @var IEventDispatcher */
  117. private $dispatcher;
  118. /** @var IUserSession */
  119. private $userSession;
  120. /** @var KnownUserService */
  121. private $knownUserService;
  122. public function __construct(
  123. LoggerInterface $logger,
  124. IConfig $config,
  125. ISecureRandom $secureRandom,
  126. IHasher $hasher,
  127. IMountManager $mountManager,
  128. IGroupManager $groupManager,
  129. IL10N $l,
  130. IFactory $l10nFactory,
  131. IProviderFactory $factory,
  132. IUserManager $userManager,
  133. IRootFolder $rootFolder,
  134. EventDispatcherInterface $legacyDispatcher,
  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->legacyDispatcher = $legacyDispatcher;
  154. $this->sharingDisabledForUsersCache = new CappedMemoryCache();
  155. // The constructor of LegacyHooks registers the listeners of share events
  156. // do not remove if those are not properly migrated
  157. $this->legacyHooks = new LegacyHooks($this->legacyDispatcher);
  158. $this->mailer = $mailer;
  159. $this->urlGenerator = $urlGenerator;
  160. $this->defaults = $defaults;
  161. $this->dispatcher = $dispatcher;
  162. $this->userSession = $userSession;
  163. $this->knownUserService = $knownUserService;
  164. }
  165. /**
  166. * Convert from a full share id to a tuple (providerId, shareId)
  167. *
  168. * @param string $id
  169. * @return string[]
  170. */
  171. private function splitFullId($id) {
  172. return explode(':', $id, 2);
  173. }
  174. /**
  175. * Verify if a password meets all requirements
  176. *
  177. * @param string $password
  178. * @throws \Exception
  179. */
  180. protected function verifyPassword($password) {
  181. if ($password === null) {
  182. // No password is set, check if this is allowed.
  183. if ($this->shareApiLinkEnforcePassword()) {
  184. throw new \InvalidArgumentException('Passwords are enforced for link and mail shares');
  185. }
  186. return;
  187. }
  188. // Let others verify the password
  189. try {
  190. $this->legacyDispatcher->dispatch(new ValidatePasswordPolicyEvent($password));
  191. } catch (HintException $e) {
  192. throw new \Exception($e->getHint());
  193. }
  194. }
  195. /**
  196. * Check for generic requirements before creating a share
  197. *
  198. * @param IShare $share
  199. * @throws \InvalidArgumentException
  200. * @throws GenericShareException
  201. *
  202. * @suppress PhanUndeclaredClassMethod
  203. */
  204. protected function generalCreateChecks(IShare $share) {
  205. if ($share->getShareType() === IShare::TYPE_USER) {
  206. // We expect a valid user as sharedWith for user shares
  207. if (!$this->userManager->userExists($share->getSharedWith())) {
  208. throw new \InvalidArgumentException('SharedWith is not a valid user');
  209. }
  210. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  211. // We expect a valid group as sharedWith for group shares
  212. if (!$this->groupManager->groupExists($share->getSharedWith())) {
  213. throw new \InvalidArgumentException('SharedWith is not a valid group');
  214. }
  215. } elseif ($share->getShareType() === IShare::TYPE_LINK) {
  216. // No check for TYPE_EMAIL here as we have a recipient for them
  217. if ($share->getSharedWith() !== null) {
  218. throw new \InvalidArgumentException('SharedWith should be empty');
  219. }
  220. } elseif ($share->getShareType() === IShare::TYPE_EMAIL) {
  221. if ($share->getSharedWith() === null) {
  222. throw new \InvalidArgumentException('SharedWith should not be empty');
  223. }
  224. } elseif ($share->getShareType() === IShare::TYPE_REMOTE) {
  225. if ($share->getSharedWith() === null) {
  226. throw new \InvalidArgumentException('SharedWith should not be empty');
  227. }
  228. } elseif ($share->getShareType() === IShare::TYPE_REMOTE_GROUP) {
  229. if ($share->getSharedWith() === null) {
  230. throw new \InvalidArgumentException('SharedWith should not be empty');
  231. }
  232. } elseif ($share->getShareType() === IShare::TYPE_CIRCLE) {
  233. $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
  234. if ($circle === null) {
  235. throw new \InvalidArgumentException('SharedWith is not a valid circle');
  236. }
  237. } elseif ($share->getShareType() === IShare::TYPE_ROOM) {
  238. } elseif ($share->getShareType() === IShare::TYPE_DECK) {
  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', $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 (!$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 GenericEvent($share);
  730. $this->legacyDispatcher->dispatch('OCP\Share::preShare', $event);
  731. if ($event->isPropagationStopped() && $event->hasArgument('error')) {
  732. throw new \Exception($event->getArgument('error'));
  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. $share = $e->getExistingShare();
  746. }
  747. // Post share event
  748. $event = new GenericEvent($share);
  749. $this->legacyDispatcher->dispatch('OCP\Share::postShare', $event);
  750. $this->dispatcher->dispatchTyped(new Share\Events\ShareCreatedEvent($share));
  751. if ($this->config->getSystemValueBool('sharing.enable_share_mail', true)
  752. && $share->getShareType() === IShare::TYPE_USER) {
  753. $mailSend = $share->getMailSend();
  754. if ($mailSend === true) {
  755. $user = $this->userManager->get($share->getSharedWith());
  756. if ($user !== null) {
  757. $emailAddress = $user->getEMailAddress();
  758. if ($emailAddress !== null && $emailAddress !== '') {
  759. $userLang = $this->l10nFactory->getUserLanguage($user);
  760. $l = $this->l10nFactory->get('lib', $userLang);
  761. $this->sendMailNotification(
  762. $l,
  763. $share->getNode()->getName(),
  764. $this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]),
  765. $share->getSharedBy(),
  766. $emailAddress,
  767. $share->getExpirationDate(),
  768. $share->getNote()
  769. );
  770. $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
  771. } else {
  772. $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
  773. }
  774. } else {
  775. $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
  776. }
  777. } else {
  778. $this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
  779. }
  780. }
  781. return $share;
  782. }
  783. /**
  784. * Send mail notifications
  785. *
  786. * This method will catch and log mail transmission errors
  787. *
  788. * @param IL10N $l Language of the recipient
  789. * @param string $filename file/folder name
  790. * @param string $link link to the file/folder
  791. * @param string $initiator user ID of share sender
  792. * @param string $shareWith email address of share receiver
  793. * @param \DateTime|null $expiration
  794. */
  795. protected function sendMailNotification(IL10N $l,
  796. $filename,
  797. $link,
  798. $initiator,
  799. $shareWith,
  800. \DateTime $expiration = null,
  801. $note = '') {
  802. $initiatorUser = $this->userManager->get($initiator);
  803. $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
  804. $message = $this->mailer->createMessage();
  805. $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
  806. 'filename' => $filename,
  807. 'link' => $link,
  808. 'initiator' => $initiatorDisplayName,
  809. 'expiration' => $expiration,
  810. 'shareWith' => $shareWith,
  811. ]);
  812. $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]));
  813. $emailTemplate->addHeader();
  814. $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
  815. $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
  816. if ($note !== '') {
  817. $emailTemplate->addBodyText(htmlspecialchars($note), $note);
  818. }
  819. $emailTemplate->addBodyText(
  820. htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
  821. $text
  822. );
  823. $emailTemplate->addBodyButton(
  824. $l->t('Open »%s«', [$filename]),
  825. $link
  826. );
  827. $message->setTo([$shareWith]);
  828. // The "From" contains the sharers name
  829. $instanceName = $this->defaults->getName();
  830. $senderName = $l->t(
  831. '%1$s via %2$s',
  832. [
  833. $initiatorDisplayName,
  834. $instanceName,
  835. ]
  836. );
  837. $message->setFrom([\OCP\Util::getDefaultEmailAddress('noreply') => $senderName]);
  838. // The "Reply-To" is set to the sharer if an mail address is configured
  839. // also the default footer contains a "Do not reply" which needs to be adjusted.
  840. $initiatorEmail = $initiatorUser->getEMailAddress();
  841. if ($initiatorEmail !== null) {
  842. $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
  843. $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan($l->getLanguageCode()) !== '' ? ' - ' . $this->defaults->getSlogan($l->getLanguageCode()) : ''));
  844. } else {
  845. $emailTemplate->addFooter('', $l->getLanguageCode());
  846. }
  847. $message->useTemplate($emailTemplate);
  848. try {
  849. $failedRecipients = $this->mailer->send($message);
  850. if (!empty($failedRecipients)) {
  851. $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
  852. return;
  853. }
  854. } catch (\Exception $e) {
  855. $this->logger->error('Share notification mail could not be sent', ['exception' => $e]);
  856. }
  857. }
  858. /**
  859. * Update a share
  860. *
  861. * @param IShare $share
  862. * @return IShare The share object
  863. * @throws \InvalidArgumentException
  864. */
  865. public function updateShare(IShare $share) {
  866. $expirationDateUpdated = false;
  867. $this->canShare($share);
  868. try {
  869. $originalShare = $this->getShareById($share->getFullId());
  870. } catch (\UnexpectedValueException $e) {
  871. throw new \InvalidArgumentException('Share does not have a full id');
  872. }
  873. // We cannot change the share type!
  874. if ($share->getShareType() !== $originalShare->getShareType()) {
  875. throw new \InvalidArgumentException('Cannot change share type');
  876. }
  877. // We can only change the recipient on user shares
  878. if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
  879. $share->getShareType() !== IShare::TYPE_USER) {
  880. throw new \InvalidArgumentException('Can only update recipient on user shares');
  881. }
  882. // Cannot share with the owner
  883. if ($share->getShareType() === IShare::TYPE_USER &&
  884. $share->getSharedWith() === $share->getShareOwner()) {
  885. throw new \InvalidArgumentException('Cannot share with the share owner');
  886. }
  887. $this->generalCreateChecks($share);
  888. if ($share->getShareType() === IShare::TYPE_USER) {
  889. $this->userCreateChecks($share);
  890. if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
  891. //Verify the expiration date
  892. $this->validateExpirationDateInternal($share);
  893. $expirationDateUpdated = true;
  894. }
  895. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  896. $this->groupCreateChecks($share);
  897. if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
  898. //Verify the expiration date
  899. $this->validateExpirationDateInternal($share);
  900. $expirationDateUpdated = true;
  901. }
  902. } elseif ($share->getShareType() === IShare::TYPE_LINK
  903. || $share->getShareType() === IShare::TYPE_EMAIL) {
  904. $this->linkCreateChecks($share);
  905. // The new password is not set again if it is the same as the old
  906. // one, unless when switching from sending by Talk to sending by
  907. // mail.
  908. $plainTextPassword = $share->getPassword();
  909. $updatedPassword = $this->updateSharePasswordIfNeeded($share, $originalShare);
  910. /**
  911. * Cannot enable the getSendPasswordByTalk if there is no password set
  912. */
  913. if (empty($plainTextPassword) && $share->getSendPasswordByTalk()) {
  914. throw new \InvalidArgumentException('Cannot enable sending the password by Talk with an empty password');
  915. }
  916. /**
  917. * If we're in a mail share, we need to force a password change
  918. * as either the user is not aware of the password or is already (received by mail)
  919. * Thus the SendPasswordByTalk feature would not make sense
  920. */
  921. if (!$updatedPassword && $share->getShareType() === IShare::TYPE_EMAIL) {
  922. if (!$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
  923. throw new \InvalidArgumentException('Cannot enable sending the password by Talk without setting a new password');
  924. }
  925. if ($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk()) {
  926. throw new \InvalidArgumentException('Cannot disable sending the password by Talk without setting a new password');
  927. }
  928. }
  929. if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
  930. // Verify the expiration date
  931. $this->validateExpirationDateLink($share);
  932. $expirationDateUpdated = true;
  933. }
  934. } elseif ($share->getShareType() === IShare::TYPE_REMOTE || $share->getShareType() === IShare::TYPE_REMOTE_GROUP) {
  935. if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
  936. //Verify the expiration date
  937. $this->validateExpirationDateInternal($share);
  938. $expirationDateUpdated = true;
  939. }
  940. }
  941. $this->pathCreateChecks($share->getNode());
  942. // Now update the share!
  943. $provider = $this->factory->getProviderForType($share->getShareType());
  944. if ($share->getShareType() === IShare::TYPE_EMAIL) {
  945. $share = $provider->update($share, $plainTextPassword);
  946. } else {
  947. $share = $provider->update($share);
  948. }
  949. if ($expirationDateUpdated === true) {
  950. \OC_Hook::emit(Share::class, 'post_set_expiration_date', [
  951. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  952. 'itemSource' => $share->getNode()->getId(),
  953. 'date' => $share->getExpirationDate(),
  954. 'uidOwner' => $share->getSharedBy(),
  955. ]);
  956. }
  957. if ($share->getPassword() !== $originalShare->getPassword()) {
  958. \OC_Hook::emit(Share::class, 'post_update_password', [
  959. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  960. 'itemSource' => $share->getNode()->getId(),
  961. 'uidOwner' => $share->getSharedBy(),
  962. 'token' => $share->getToken(),
  963. 'disabled' => is_null($share->getPassword()),
  964. ]);
  965. }
  966. if ($share->getPermissions() !== $originalShare->getPermissions()) {
  967. if ($this->userManager->userExists($share->getShareOwner())) {
  968. $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  969. } else {
  970. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  971. }
  972. \OC_Hook::emit(Share::class, 'post_update_permissions', [
  973. 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
  974. 'itemSource' => $share->getNode()->getId(),
  975. 'shareType' => $share->getShareType(),
  976. 'shareWith' => $share->getSharedWith(),
  977. 'uidOwner' => $share->getSharedBy(),
  978. 'permissions' => $share->getPermissions(),
  979. 'attributes' => $share->getAttributes() !== null ? $share->getAttributes()->toArray() : null,
  980. 'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
  981. ]);
  982. }
  983. return $share;
  984. }
  985. /**
  986. * Accept a share.
  987. *
  988. * @param IShare $share
  989. * @param string $recipientId
  990. * @return IShare The share object
  991. * @throws \InvalidArgumentException
  992. * @since 9.0.0
  993. */
  994. public function acceptShare(IShare $share, string $recipientId): IShare {
  995. [$providerId,] = $this->splitFullId($share->getFullId());
  996. $provider = $this->factory->getProvider($providerId);
  997. if (!method_exists($provider, 'acceptShare')) {
  998. // TODO FIX ME
  999. throw new \InvalidArgumentException('Share provider does not support accepting');
  1000. }
  1001. $provider->acceptShare($share, $recipientId);
  1002. $event = new GenericEvent($share);
  1003. $this->legacyDispatcher->dispatch('OCP\Share::postAcceptShare', $event);
  1004. return $share;
  1005. }
  1006. /**
  1007. * Updates the password of the given share if it is not the same as the
  1008. * password of the original share.
  1009. *
  1010. * @param IShare $share the share to update its password.
  1011. * @param IShare $originalShare the original share to compare its
  1012. * password with.
  1013. * @return boolean whether the password was updated or not.
  1014. */
  1015. private function updateSharePasswordIfNeeded(IShare $share, IShare $originalShare) {
  1016. $passwordsAreDifferent = ($share->getPassword() !== $originalShare->getPassword()) &&
  1017. (($share->getPassword() !== null && $originalShare->getPassword() === null) ||
  1018. ($share->getPassword() === null && $originalShare->getPassword() !== null) ||
  1019. ($share->getPassword() !== null && $originalShare->getPassword() !== null &&
  1020. !$this->hasher->verify($share->getPassword(), $originalShare->getPassword())));
  1021. // Password updated.
  1022. if ($passwordsAreDifferent) {
  1023. //Verify the password
  1024. $this->verifyPassword($share->getPassword());
  1025. // If a password is set. Hash it!
  1026. if (!empty($share->getPassword())) {
  1027. $share->setPassword($this->hasher->hash($share->getPassword()));
  1028. if ($share->getShareType() === IShare::TYPE_EMAIL) {
  1029. // Shares shared by email have temporary passwords
  1030. $this->setSharePasswordExpirationTime($share);
  1031. }
  1032. return true;
  1033. } else {
  1034. // Empty string and null are seen as NOT password protected
  1035. $share->setPassword(null);
  1036. if ($share->getShareType() === IShare::TYPE_EMAIL) {
  1037. $share->setPasswordExpirationTime(null);
  1038. }
  1039. return true;
  1040. }
  1041. } else {
  1042. // Reset the password to the original one, as it is either the same
  1043. // as the "new" password or a hashed version of it.
  1044. $share->setPassword($originalShare->getPassword());
  1045. }
  1046. return false;
  1047. }
  1048. /**
  1049. * Set the share's password expiration time
  1050. */
  1051. private function setSharePasswordExpirationTime(IShare $share): void {
  1052. if (!$this->config->getSystemValue('sharing.enable_mail_link_password_expiration', false)) {
  1053. // Sets password expiration date to NULL
  1054. $share->setPasswordExpirationTime();
  1055. return;
  1056. }
  1057. // Sets password expiration date
  1058. $expirationTime = null;
  1059. $now = new \DateTime();
  1060. $expirationInterval = $this->config->getSystemValue('sharing.mail_link_password_expiration_interval', 3600);
  1061. $expirationTime = $now->add(new \DateInterval('PT' . $expirationInterval . 'S'));
  1062. $share->setPasswordExpirationTime($expirationTime);
  1063. }
  1064. /**
  1065. * Delete all the children of this share
  1066. * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
  1067. *
  1068. * @param IShare $share
  1069. * @return IShare[] List of deleted shares
  1070. */
  1071. protected function deleteChildren(IShare $share) {
  1072. $deletedShares = [];
  1073. $provider = $this->factory->getProviderForType($share->getShareType());
  1074. foreach ($provider->getChildren($share) as $child) {
  1075. $deletedChildren = $this->deleteChildren($child);
  1076. $deletedShares = array_merge($deletedShares, $deletedChildren);
  1077. $provider->delete($child);
  1078. $this->dispatcher->dispatchTyped(new Share\Events\ShareDeletedEvent($child));
  1079. $deletedShares[] = $child;
  1080. }
  1081. return $deletedShares;
  1082. }
  1083. /**
  1084. * Delete a share
  1085. *
  1086. * @param IShare $share
  1087. * @throws ShareNotFound
  1088. * @throws \InvalidArgumentException
  1089. */
  1090. public function deleteShare(IShare $share) {
  1091. try {
  1092. $share->getFullId();
  1093. } catch (\UnexpectedValueException $e) {
  1094. throw new \InvalidArgumentException('Share does not have a full id');
  1095. }
  1096. $event = new GenericEvent($share);
  1097. $this->legacyDispatcher->dispatch('OCP\Share::preUnshare', $event);
  1098. // Get all children and delete them as well
  1099. $deletedShares = $this->deleteChildren($share);
  1100. // Do the actual delete
  1101. $provider = $this->factory->getProviderForType($share->getShareType());
  1102. $provider->delete($share);
  1103. $this->dispatcher->dispatchTyped(new Share\Events\ShareDeletedEvent($share));
  1104. // All the deleted shares caused by this delete
  1105. $deletedShares[] = $share;
  1106. // Emit post hook
  1107. $event->setArgument('deletedShares', $deletedShares);
  1108. $this->legacyDispatcher->dispatch('OCP\Share::postUnshare', $event);
  1109. }
  1110. /**
  1111. * Unshare a file as the recipient.
  1112. * This can be different from a regular delete for example when one of
  1113. * the users in a groups deletes that share. But the provider should
  1114. * handle this.
  1115. *
  1116. * @param IShare $share
  1117. * @param string $recipientId
  1118. */
  1119. public function deleteFromSelf(IShare $share, $recipientId) {
  1120. [$providerId,] = $this->splitFullId($share->getFullId());
  1121. $provider = $this->factory->getProvider($providerId);
  1122. $provider->deleteFromSelf($share, $recipientId);
  1123. $event = new GenericEvent($share);
  1124. $this->legacyDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
  1125. }
  1126. public function restoreShare(IShare $share, string $recipientId): IShare {
  1127. [$providerId,] = $this->splitFullId($share->getFullId());
  1128. $provider = $this->factory->getProvider($providerId);
  1129. return $provider->restore($share, $recipientId);
  1130. }
  1131. /**
  1132. * @inheritdoc
  1133. */
  1134. public function moveShare(IShare $share, $recipientId) {
  1135. if ($share->getShareType() === IShare::TYPE_LINK
  1136. || $share->getShareType() === IShare::TYPE_EMAIL) {
  1137. throw new \InvalidArgumentException('Cannot change target of link share');
  1138. }
  1139. if ($share->getShareType() === IShare::TYPE_USER && $share->getSharedWith() !== $recipientId) {
  1140. throw new \InvalidArgumentException('Invalid recipient');
  1141. }
  1142. if ($share->getShareType() === IShare::TYPE_GROUP) {
  1143. $sharedWith = $this->groupManager->get($share->getSharedWith());
  1144. if (is_null($sharedWith)) {
  1145. throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
  1146. }
  1147. $recipient = $this->userManager->get($recipientId);
  1148. if (!$sharedWith->inGroup($recipient)) {
  1149. throw new \InvalidArgumentException('Invalid recipient');
  1150. }
  1151. }
  1152. [$providerId,] = $this->splitFullId($share->getFullId());
  1153. $provider = $this->factory->getProvider($providerId);
  1154. return $provider->move($share, $recipientId);
  1155. }
  1156. public function getSharesInFolder($userId, Folder $node, $reshares = false, $shallow = true) {
  1157. $providers = $this->factory->getAllProviders();
  1158. return array_reduce($providers, function ($shares, IShareProvider $provider) use ($userId, $node, $reshares, $shallow) {
  1159. $newShares = $provider->getSharesInFolder($userId, $node, $reshares, $shallow);
  1160. foreach ($newShares as $fid => $data) {
  1161. if (!isset($shares[$fid])) {
  1162. $shares[$fid] = [];
  1163. }
  1164. $shares[$fid] = array_merge($shares[$fid], $data);
  1165. }
  1166. return $shares;
  1167. }, []);
  1168. }
  1169. /**
  1170. * @inheritdoc
  1171. */
  1172. public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
  1173. if ($path !== null &&
  1174. !($path instanceof \OCP\Files\File) &&
  1175. !($path instanceof \OCP\Files\Folder)) {
  1176. throw new \InvalidArgumentException('invalid path');
  1177. }
  1178. try {
  1179. $provider = $this->factory->getProviderForType($shareType);
  1180. } catch (ProviderException $e) {
  1181. return [];
  1182. }
  1183. $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
  1184. /*
  1185. * Work around so we don't return expired shares but still follow
  1186. * proper pagination.
  1187. */
  1188. $shares2 = [];
  1189. while (true) {
  1190. $added = 0;
  1191. foreach ($shares as $share) {
  1192. try {
  1193. $this->checkExpireDate($share);
  1194. } catch (ShareNotFound $e) {
  1195. //Ignore since this basically means the share is deleted
  1196. continue;
  1197. }
  1198. $added++;
  1199. $shares2[] = $share;
  1200. if (count($shares2) === $limit) {
  1201. break;
  1202. }
  1203. }
  1204. // If we did not fetch more shares than the limit then there are no more shares
  1205. if (count($shares) < $limit) {
  1206. break;
  1207. }
  1208. if (count($shares2) === $limit) {
  1209. break;
  1210. }
  1211. // If there was no limit on the select we are done
  1212. if ($limit === -1) {
  1213. break;
  1214. }
  1215. $offset += $added;
  1216. // Fetch again $limit shares
  1217. $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
  1218. // No more shares means we are done
  1219. if (empty($shares)) {
  1220. break;
  1221. }
  1222. }
  1223. $shares = $shares2;
  1224. return $shares;
  1225. }
  1226. /**
  1227. * @inheritdoc
  1228. */
  1229. public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
  1230. try {
  1231. $provider = $this->factory->getProviderForType($shareType);
  1232. } catch (ProviderException $e) {
  1233. return [];
  1234. }
  1235. $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
  1236. // remove all shares which are already expired
  1237. foreach ($shares as $key => $share) {
  1238. try {
  1239. $this->checkExpireDate($share);
  1240. } catch (ShareNotFound $e) {
  1241. unset($shares[$key]);
  1242. }
  1243. }
  1244. return $shares;
  1245. }
  1246. /**
  1247. * @inheritdoc
  1248. */
  1249. public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
  1250. $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
  1251. // Only get deleted shares
  1252. $shares = array_filter($shares, function (IShare $share) {
  1253. return $share->getPermissions() === 0;
  1254. });
  1255. // Only get shares where the owner still exists
  1256. $shares = array_filter($shares, function (IShare $share) {
  1257. return $this->userManager->userExists($share->getShareOwner());
  1258. });
  1259. return $shares;
  1260. }
  1261. /**
  1262. * @inheritdoc
  1263. */
  1264. public function getShareById($id, $recipient = null) {
  1265. if ($id === null) {
  1266. throw new ShareNotFound();
  1267. }
  1268. [$providerId, $id] = $this->splitFullId($id);
  1269. try {
  1270. $provider = $this->factory->getProvider($providerId);
  1271. } catch (ProviderException $e) {
  1272. throw new ShareNotFound();
  1273. }
  1274. $share = $provider->getShareById($id, $recipient);
  1275. $this->checkExpireDate($share);
  1276. return $share;
  1277. }
  1278. /**
  1279. * Get all the shares for a given path
  1280. *
  1281. * @param \OCP\Files\Node $path
  1282. * @param int $page
  1283. * @param int $perPage
  1284. *
  1285. * @return Share[]
  1286. */
  1287. public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
  1288. return [];
  1289. }
  1290. /**
  1291. * Get the share by token possible with password
  1292. *
  1293. * @param string $token
  1294. * @return IShare
  1295. *
  1296. * @throws ShareNotFound
  1297. */
  1298. public function getShareByToken($token) {
  1299. // tokens cannot be valid local user names
  1300. if ($this->userManager->userExists($token)) {
  1301. throw new ShareNotFound();
  1302. }
  1303. $share = null;
  1304. try {
  1305. if ($this->shareApiAllowLinks()) {
  1306. $provider = $this->factory->getProviderForType(IShare::TYPE_LINK);
  1307. $share = $provider->getShareByToken($token);
  1308. }
  1309. } catch (ProviderException $e) {
  1310. } catch (ShareNotFound $e) {
  1311. }
  1312. // If it is not a link share try to fetch a federated share by token
  1313. if ($share === null) {
  1314. try {
  1315. $provider = $this->factory->getProviderForType(IShare::TYPE_REMOTE);
  1316. $share = $provider->getShareByToken($token);
  1317. } catch (ProviderException $e) {
  1318. } catch (ShareNotFound $e) {
  1319. }
  1320. }
  1321. // If it is not a link share try to fetch a mail share by token
  1322. if ($share === null && $this->shareProviderExists(IShare::TYPE_EMAIL)) {
  1323. try {
  1324. $provider = $this->factory->getProviderForType(IShare::TYPE_EMAIL);
  1325. $share = $provider->getShareByToken($token);
  1326. } catch (ProviderException $e) {
  1327. } catch (ShareNotFound $e) {
  1328. }
  1329. }
  1330. if ($share === null && $this->shareProviderExists(IShare::TYPE_CIRCLE)) {
  1331. try {
  1332. $provider = $this->factory->getProviderForType(IShare::TYPE_CIRCLE);
  1333. $share = $provider->getShareByToken($token);
  1334. } catch (ProviderException $e) {
  1335. } catch (ShareNotFound $e) {
  1336. }
  1337. }
  1338. if ($share === null && $this->shareProviderExists(IShare::TYPE_ROOM)) {
  1339. try {
  1340. $provider = $this->factory->getProviderForType(IShare::TYPE_ROOM);
  1341. $share = $provider->getShareByToken($token);
  1342. } catch (ProviderException $e) {
  1343. } catch (ShareNotFound $e) {
  1344. }
  1345. }
  1346. if ($share === null) {
  1347. throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
  1348. }
  1349. $this->checkExpireDate($share);
  1350. /*
  1351. * Reduce the permissions for link or email shares if public upload is not enabled
  1352. */
  1353. if (($share->getShareType() === IShare::TYPE_LINK || $share->getShareType() === IShare::TYPE_EMAIL)
  1354. && !$this->shareApiLinkAllowPublicUpload()) {
  1355. $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
  1356. }
  1357. return $share;
  1358. }
  1359. protected function checkExpireDate($share) {
  1360. if ($share->isExpired()) {
  1361. $this->deleteShare($share);
  1362. throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
  1363. }
  1364. }
  1365. /**
  1366. * Verify the password of a public share
  1367. *
  1368. * @param IShare $share
  1369. * @param string $password
  1370. * @return bool
  1371. */
  1372. public function checkPassword(IShare $share, $password) {
  1373. $passwordProtected = $share->getShareType() !== IShare::TYPE_LINK
  1374. || $share->getShareType() !== IShare::TYPE_EMAIL
  1375. || $share->getShareType() !== IShare::TYPE_CIRCLE;
  1376. if (!$passwordProtected) {
  1377. //TODO maybe exception?
  1378. return false;
  1379. }
  1380. if ($password === null || $share->getPassword() === null) {
  1381. return false;
  1382. }
  1383. // Makes sure password hasn't expired
  1384. $expirationTime = $share->getPasswordExpirationTime();
  1385. if ($expirationTime !== null && $expirationTime < new \DateTime()) {
  1386. return false;
  1387. }
  1388. $newHash = '';
  1389. if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
  1390. return false;
  1391. }
  1392. if (!empty($newHash)) {
  1393. $share->setPassword($newHash);
  1394. $provider = $this->factory->getProviderForType($share->getShareType());
  1395. $provider->update($share);
  1396. }
  1397. return true;
  1398. }
  1399. /**
  1400. * @inheritdoc
  1401. */
  1402. public function userDeleted($uid) {
  1403. $types = [IShare::TYPE_USER, IShare::TYPE_GROUP, IShare::TYPE_LINK, IShare::TYPE_REMOTE, IShare::TYPE_EMAIL];
  1404. foreach ($types as $type) {
  1405. try {
  1406. $provider = $this->factory->getProviderForType($type);
  1407. } catch (ProviderException $e) {
  1408. continue;
  1409. }
  1410. $provider->userDeleted($uid, $type);
  1411. }
  1412. }
  1413. /**
  1414. * @inheritdoc
  1415. */
  1416. public function groupDeleted($gid) {
  1417. $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
  1418. $provider->groupDeleted($gid);
  1419. $excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
  1420. if ($excludedGroups === '') {
  1421. return;
  1422. }
  1423. $excludedGroups = json_decode($excludedGroups, true);
  1424. if (json_last_error() !== JSON_ERROR_NONE) {
  1425. return;
  1426. }
  1427. $excludedGroups = array_diff($excludedGroups, [$gid]);
  1428. $this->config->setAppValue('core', 'shareapi_exclude_groups_list', json_encode($excludedGroups));
  1429. }
  1430. /**
  1431. * @inheritdoc
  1432. */
  1433. public function userDeletedFromGroup($uid, $gid) {
  1434. $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
  1435. $provider->userDeletedFromGroup($uid, $gid);
  1436. }
  1437. /**
  1438. * Get access list to a path. This means
  1439. * all the users that can access a given path.
  1440. *
  1441. * Consider:
  1442. * -root
  1443. * |-folder1 (23)
  1444. * |-folder2 (32)
  1445. * |-fileA (42)
  1446. *
  1447. * fileA is shared with user1 and user1@server1
  1448. * folder2 is shared with group2 (user4 is a member of group2)
  1449. * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
  1450. *
  1451. * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
  1452. * [
  1453. * users => [
  1454. * 'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
  1455. * 'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
  1456. * 'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
  1457. * ],
  1458. * remote => [
  1459. * 'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
  1460. * 'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
  1461. * ],
  1462. * public => bool
  1463. * mail => bool
  1464. * ]
  1465. *
  1466. * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
  1467. * [
  1468. * users => ['user1', 'user2', 'user4'],
  1469. * remote => bool,
  1470. * public => bool
  1471. * mail => bool
  1472. * ]
  1473. *
  1474. * This is required for encryption/activity
  1475. *
  1476. * @param \OCP\Files\Node $path
  1477. * @param bool $recursive Should we check all parent folders as well
  1478. * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
  1479. * @return array
  1480. */
  1481. public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
  1482. $owner = $path->getOwner();
  1483. if ($owner === null) {
  1484. return [];
  1485. }
  1486. $owner = $owner->getUID();
  1487. if ($currentAccess) {
  1488. $al = ['users' => [], 'remote' => [], 'public' => false];
  1489. } else {
  1490. $al = ['users' => [], 'remote' => false, 'public' => false];
  1491. }
  1492. if (!$this->userManager->userExists($owner)) {
  1493. return $al;
  1494. }
  1495. //Get node for the owner and correct the owner in case of external storage
  1496. $userFolder = $this->rootFolder->getUserFolder($owner);
  1497. if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
  1498. $nodes = $userFolder->getById($path->getId());
  1499. $path = array_shift($nodes);
  1500. if ($path === null || $path->getOwner() === null) {
  1501. return [];
  1502. }
  1503. $owner = $path->getOwner()->getUID();
  1504. }
  1505. $providers = $this->factory->getAllProviders();
  1506. /** @var Node[] $nodes */
  1507. $nodes = [];
  1508. if ($currentAccess) {
  1509. $ownerPath = $path->getPath();
  1510. $ownerPath = explode('/', $ownerPath, 4);
  1511. if (count($ownerPath) < 4) {
  1512. $ownerPath = '';
  1513. } else {
  1514. $ownerPath = $ownerPath[3];
  1515. }
  1516. $al['users'][$owner] = [
  1517. 'node_id' => $path->getId(),
  1518. 'node_path' => '/' . $ownerPath,
  1519. ];
  1520. } else {
  1521. $al['users'][] = $owner;
  1522. }
  1523. // Collect all the shares
  1524. while ($path->getPath() !== $userFolder->getPath()) {
  1525. $nodes[] = $path;
  1526. if (!$recursive) {
  1527. break;
  1528. }
  1529. $path = $path->getParent();
  1530. }
  1531. foreach ($providers as $provider) {
  1532. $tmp = $provider->getAccessList($nodes, $currentAccess);
  1533. foreach ($tmp as $k => $v) {
  1534. if (isset($al[$k])) {
  1535. if (is_array($al[$k])) {
  1536. if ($currentAccess) {
  1537. $al[$k] += $v;
  1538. } else {
  1539. $al[$k] = array_merge($al[$k], $v);
  1540. $al[$k] = array_unique($al[$k]);
  1541. $al[$k] = array_values($al[$k]);
  1542. }
  1543. } else {
  1544. $al[$k] = $al[$k] || $v;
  1545. }
  1546. } else {
  1547. $al[$k] = $v;
  1548. }
  1549. }
  1550. }
  1551. return $al;
  1552. }
  1553. /**
  1554. * Create a new share
  1555. *
  1556. * @return IShare
  1557. */
  1558. public function newShare() {
  1559. return new \OC\Share20\Share($this->rootFolder, $this->userManager);
  1560. }
  1561. /**
  1562. * Is the share API enabled
  1563. *
  1564. * @return bool
  1565. */
  1566. public function shareApiEnabled() {
  1567. return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
  1568. }
  1569. /**
  1570. * Is public link sharing enabled
  1571. *
  1572. * @return bool
  1573. */
  1574. public function shareApiAllowLinks() {
  1575. if ($this->config->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
  1576. return false;
  1577. }
  1578. $user = $this->userSession->getUser();
  1579. if ($user) {
  1580. $excludedGroups = json_decode($this->config->getAppValue('core', 'shareapi_allow_links_exclude_groups', '[]'));
  1581. if ($excludedGroups) {
  1582. $userGroups = $this->groupManager->getUserGroupIds($user);
  1583. return !(bool)array_intersect($excludedGroups, $userGroups);
  1584. }
  1585. }
  1586. return true;
  1587. }
  1588. /**
  1589. * Is password on public link requires
  1590. *
  1591. * @param bool Check group membership exclusion
  1592. * @return bool
  1593. */
  1594. public function shareApiLinkEnforcePassword(bool $checkGroupMembership = true) {
  1595. $excludedGroups = $this->config->getAppValue('core', 'shareapi_enforce_links_password_excluded_groups', '');
  1596. if ($excludedGroups !== '' && $checkGroupMembership) {
  1597. $excludedGroups = json_decode($excludedGroups);
  1598. $user = $this->userSession->getUser();
  1599. if ($user) {
  1600. $userGroups = $this->groupManager->getUserGroupIds($user);
  1601. if ((bool)array_intersect($excludedGroups, $userGroups)) {
  1602. return false;
  1603. }
  1604. }
  1605. }
  1606. return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
  1607. }
  1608. /**
  1609. * Is default link expire date enabled
  1610. *
  1611. * @return bool
  1612. */
  1613. public function shareApiLinkDefaultExpireDate() {
  1614. return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
  1615. }
  1616. /**
  1617. * Is default link expire date enforced
  1618. *`
  1619. *
  1620. * @return bool
  1621. */
  1622. public function shareApiLinkDefaultExpireDateEnforced() {
  1623. return $this->shareApiLinkDefaultExpireDate() &&
  1624. $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
  1625. }
  1626. /**
  1627. * Number of default link expire days
  1628. *
  1629. * @return int
  1630. */
  1631. public function shareApiLinkDefaultExpireDays() {
  1632. return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
  1633. }
  1634. /**
  1635. * Is default internal expire date enabled
  1636. *
  1637. * @return bool
  1638. */
  1639. public function shareApiInternalDefaultExpireDate(): bool {
  1640. return $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
  1641. }
  1642. /**
  1643. * Is default remote expire date enabled
  1644. *
  1645. * @return bool
  1646. */
  1647. public function shareApiRemoteDefaultExpireDate(): bool {
  1648. return $this->config->getAppValue('core', 'shareapi_default_remote_expire_date', 'no') === 'yes';
  1649. }
  1650. /**
  1651. * Is default expire date enforced
  1652. *
  1653. * @return bool
  1654. */
  1655. public function shareApiInternalDefaultExpireDateEnforced(): bool {
  1656. return $this->shareApiInternalDefaultExpireDate() &&
  1657. $this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
  1658. }
  1659. /**
  1660. * Is default expire date enforced for remote shares
  1661. *
  1662. * @return bool
  1663. */
  1664. public function shareApiRemoteDefaultExpireDateEnforced(): bool {
  1665. return $this->shareApiRemoteDefaultExpireDate() &&
  1666. $this->config->getAppValue('core', 'shareapi_enforce_remote_expire_date', 'no') === 'yes';
  1667. }
  1668. /**
  1669. * Number of default expire days
  1670. *
  1671. * @return int
  1672. */
  1673. public function shareApiInternalDefaultExpireDays(): int {
  1674. return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
  1675. }
  1676. /**
  1677. * Number of default expire days for remote shares
  1678. *
  1679. * @return int
  1680. */
  1681. public function shareApiRemoteDefaultExpireDays(): int {
  1682. return (int)$this->config->getAppValue('core', 'shareapi_remote_expire_after_n_days', '7');
  1683. }
  1684. /**
  1685. * Allow public upload on link shares
  1686. *
  1687. * @return bool
  1688. */
  1689. public function shareApiLinkAllowPublicUpload() {
  1690. return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
  1691. }
  1692. /**
  1693. * check if user can only share with group members
  1694. *
  1695. * @return bool
  1696. */
  1697. public function shareWithGroupMembersOnly() {
  1698. return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
  1699. }
  1700. /**
  1701. * Check if users can share with groups
  1702. *
  1703. * @return bool
  1704. */
  1705. public function allowGroupSharing() {
  1706. return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
  1707. }
  1708. public function allowEnumeration(): bool {
  1709. return $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
  1710. }
  1711. public function limitEnumerationToGroups(): bool {
  1712. return $this->allowEnumeration() &&
  1713. $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
  1714. }
  1715. public function limitEnumerationToPhone(): bool {
  1716. return $this->allowEnumeration() &&
  1717. $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
  1718. }
  1719. public function allowEnumerationFullMatch(): bool {
  1720. return $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_full_match', 'yes') === 'yes';
  1721. }
  1722. public function matchEmail(): bool {
  1723. return $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_full_match_email', 'yes') === 'yes';
  1724. }
  1725. public function ignoreSecondDisplayName(): bool {
  1726. return $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_full_match_ignore_second_dn', 'no') === 'yes';
  1727. }
  1728. public function currentUserCanEnumerateTargetUser(?IUser $currentUser, IUser $targetUser): bool {
  1729. if ($this->allowEnumerationFullMatch()) {
  1730. return true;
  1731. }
  1732. if (!$this->allowEnumeration()) {
  1733. return false;
  1734. }
  1735. if (!$this->limitEnumerationToPhone() && !$this->limitEnumerationToGroups()) {
  1736. // Enumeration is enabled and not restricted: OK
  1737. return true;
  1738. }
  1739. if (!$currentUser instanceof IUser) {
  1740. // Enumeration restrictions require an account
  1741. return false;
  1742. }
  1743. // Enumeration is limited to phone match
  1744. if ($this->limitEnumerationToPhone() && $this->knownUserService->isKnownToUser($currentUser->getUID(), $targetUser->getUID())) {
  1745. return true;
  1746. }
  1747. // Enumeration is limited to groups
  1748. if ($this->limitEnumerationToGroups()) {
  1749. $currentUserGroupIds = $this->groupManager->getUserGroupIds($currentUser);
  1750. $targetUserGroupIds = $this->groupManager->getUserGroupIds($targetUser);
  1751. if (!empty(array_intersect($currentUserGroupIds, $targetUserGroupIds))) {
  1752. return true;
  1753. }
  1754. }
  1755. return false;
  1756. }
  1757. /**
  1758. * Copied from \OC_Util::isSharingDisabledForUser
  1759. *
  1760. * TODO: Deprecate function from OC_Util
  1761. *
  1762. * @param string $userId
  1763. * @return bool
  1764. */
  1765. public function sharingDisabledForUser($userId) {
  1766. if ($userId === null) {
  1767. return false;
  1768. }
  1769. if (isset($this->sharingDisabledForUsersCache[$userId])) {
  1770. return $this->sharingDisabledForUsersCache[$userId];
  1771. }
  1772. if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
  1773. $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
  1774. $excludedGroups = json_decode($groupsList);
  1775. if (is_null($excludedGroups)) {
  1776. $excludedGroups = explode(',', $groupsList);
  1777. $newValue = json_encode($excludedGroups);
  1778. $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
  1779. }
  1780. $user = $this->userManager->get($userId);
  1781. $usersGroups = $this->groupManager->getUserGroupIds($user);
  1782. if (!empty($usersGroups)) {
  1783. $remainingGroups = array_diff($usersGroups, $excludedGroups);
  1784. // if the user is only in groups which are disabled for sharing then
  1785. // sharing is also disabled for the user
  1786. if (empty($remainingGroups)) {
  1787. $this->sharingDisabledForUsersCache[$userId] = true;
  1788. return true;
  1789. }
  1790. }
  1791. }
  1792. $this->sharingDisabledForUsersCache[$userId] = false;
  1793. return false;
  1794. }
  1795. /**
  1796. * @inheritdoc
  1797. */
  1798. public function outgoingServer2ServerSharesAllowed() {
  1799. return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
  1800. }
  1801. /**
  1802. * @inheritdoc
  1803. */
  1804. public function outgoingServer2ServerGroupSharesAllowed() {
  1805. return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
  1806. }
  1807. /**
  1808. * @inheritdoc
  1809. */
  1810. public function shareProviderExists($shareType) {
  1811. try {
  1812. $this->factory->getProviderForType($shareType);
  1813. } catch (ProviderException $e) {
  1814. return false;
  1815. }
  1816. return true;
  1817. }
  1818. public function registerShareProvider(string $shareProviderClass): void {
  1819. $this->factory->registerProvider($shareProviderClass);
  1820. }
  1821. public function getAllShares(): iterable {
  1822. $providers = $this->factory->getAllProviders();
  1823. foreach ($providers as $provider) {
  1824. yield from $provider->getAllShares();
  1825. }
  1826. }
  1827. }