Manager.php 66 KB

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