Manager.php 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  10. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  11. * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author John Molakvoæ <skjnldsv@protonmail.com>
  14. * @author Julius Härtl <jus@bitgrid.net>
  15. * @author Lukas Reschke <lukas@statuscode.ch>
  16. * @author Maxence Lange <maxence@artificial-owl.com>
  17. * @author Maxence Lange <maxence@nextcloud.com>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author Pauli Järvinen <pauli.jarvinen@gmail.com>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Roeland Jago Douma <roeland@famdouma.nl>
  22. * @author Samuel <faust64@gmail.com>
  23. * @author szaimen <szaimen@e.mail.de>
  24. * @author Valdnet <47037905+Valdnet@users.noreply.github.com>
  25. * @author Vincent Petry <vincent@nextcloud.com>
  26. *
  27. * @license AGPL-3.0
  28. *
  29. * This code is free software: you can redistribute it and/or modify
  30. * it under the terms of the GNU Affero General Public License, version 3,
  31. * as published by the Free Software Foundation.
  32. *
  33. * This program is distributed in the hope that it will be useful,
  34. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  35. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  36. * GNU Affero General Public License for more details.
  37. *
  38. * You should have received a copy of the GNU Affero General Public License, version 3,
  39. * along with this program. If not, see <http://www.gnu.org/licenses/>
  40. *
  41. */
  42. namespace OC\Share20;
  43. use OC\Files\Mount\MoveableMount;
  44. use OC\KnownUser\KnownUserService;
  45. use OC\Share20\Exception\ProviderException;
  46. use OCA\Files_Sharing\AppInfo\Application;
  47. use OCA\Files_Sharing\ISharedStorage;
  48. use OCP\EventDispatcher\IEventDispatcher;
  49. use OCP\Files\File;
  50. use OCP\Files\Folder;
  51. use OCP\Files\IRootFolder;
  52. use OCP\Files\Mount\IMountManager;
  53. use OCP\Files\Node;
  54. use OCP\HintException;
  55. use OCP\IConfig;
  56. use OCP\IGroupManager;
  57. use OCP\IL10N;
  58. use OCP\IURLGenerator;
  59. use OCP\IUser;
  60. use OCP\IUserManager;
  61. use OCP\IUserSession;
  62. use OCP\L10N\IFactory;
  63. use OCP\Mail\IMailer;
  64. use OCP\Security\Events\ValidatePasswordPolicyEvent;
  65. use OCP\Security\IHasher;
  66. use OCP\Security\ISecureRandom;
  67. use OCP\Share;
  68. use OCP\Share\Events\BeforeShareDeletedEvent;
  69. use OCP\Share\Events\ShareAcceptedEvent;
  70. use OCP\Share\Events\ShareCreatedEvent;
  71. use OCP\Share\Events\ShareDeletedEvent;
  72. use OCP\Share\Events\ShareDeletedFromSelfEvent;
  73. use OCP\Share\Exceptions\AlreadySharedException;
  74. use OCP\Share\Exceptions\GenericShareException;
  75. use OCP\Share\Exceptions\ShareNotFound;
  76. use OCP\Share\IManager;
  77. use OCP\Share\IProviderFactory;
  78. use OCP\Share\IShare;
  79. use OCP\Share\IShareProvider;
  80. use Psr\Log\LoggerInterface;
  81. /**
  82. * This class is the communication hub for all sharing related operations.
  83. */
  84. class Manager implements IManager {
  85. /** @var IProviderFactory */
  86. private $factory;
  87. private LoggerInterface $logger;
  88. /** @var IConfig */
  89. private $config;
  90. /** @var ISecureRandom */
  91. private $secureRandom;
  92. /** @var IHasher */
  93. private $hasher;
  94. /** @var IMountManager */
  95. private $mountManager;
  96. /** @var IGroupManager */
  97. private $groupManager;
  98. /** @var IL10N */
  99. private $l;
  100. /** @var IFactory */
  101. private $l10nFactory;
  102. /** @var IUserManager */
  103. private $userManager;
  104. /** @var IRootFolder */
  105. private $rootFolder;
  106. /** @var LegacyHooks */
  107. private $legacyHooks;
  108. /** @var IMailer */
  109. private $mailer;
  110. /** @var IURLGenerator */
  111. private $urlGenerator;
  112. /** @var \OC_Defaults */
  113. private $defaults;
  114. /** @var IEventDispatcher */
  115. private $dispatcher;
  116. /** @var IUserSession */
  117. private $userSession;
  118. /** @var KnownUserService */
  119. private $knownUserService;
  120. private ShareDisableChecker $shareDisableChecker;
  121. public function __construct(
  122. LoggerInterface $logger,
  123. IConfig $config,
  124. ISecureRandom $secureRandom,
  125. IHasher $hasher,
  126. IMountManager $mountManager,
  127. IGroupManager $groupManager,
  128. IL10N $l,
  129. IFactory $l10nFactory,
  130. IProviderFactory $factory,
  131. IUserManager $userManager,
  132. IRootFolder $rootFolder,
  133. IMailer $mailer,
  134. IURLGenerator $urlGenerator,
  135. \OC_Defaults $defaults,
  136. IEventDispatcher $dispatcher,
  137. IUserSession $userSession,
  138. KnownUserService $knownUserService,
  139. ShareDisableChecker $shareDisableChecker
  140. ) {
  141. $this->logger = $logger;
  142. $this->config = $config;
  143. $this->secureRandom = $secureRandom;
  144. $this->hasher = $hasher;
  145. $this->mountManager = $mountManager;
  146. $this->groupManager = $groupManager;
  147. $this->l = $l;
  148. $this->l10nFactory = $l10nFactory;
  149. $this->factory = $factory;
  150. $this->userManager = $userManager;
  151. $this->rootFolder = $rootFolder;
  152. // The constructor of LegacyHooks registers the listeners of share events
  153. // do not remove if those are not properly migrated
  154. $this->legacyHooks = new LegacyHooks($dispatcher);
  155. $this->mailer = $mailer;
  156. $this->urlGenerator = $urlGenerator;
  157. $this->defaults = $defaults;
  158. $this->dispatcher = $dispatcher;
  159. $this->userSession = $userSession;
  160. $this->knownUserService = $knownUserService;
  161. $this->shareDisableChecker = $shareDisableChecker;
  162. }
  163. /**
  164. * Convert from a full share id to a tuple (providerId, shareId)
  165. *
  166. * @param string $id
  167. * @return string[]
  168. */
  169. private function splitFullId($id) {
  170. return explode(':', $id, 2);
  171. }
  172. /**
  173. * Verify if a password meets all requirements
  174. *
  175. * @param string $password
  176. * @throws \Exception
  177. */
  178. protected function verifyPassword($password) {
  179. if ($password === null) {
  180. // No password is set, check if this is allowed.
  181. if ($this->shareApiLinkEnforcePassword()) {
  182. throw new \InvalidArgumentException('Passwords are enforced for link and mail shares');
  183. }
  184. return;
  185. }
  186. // Let others verify the password
  187. try {
  188. $this->dispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
  189. } catch (HintException $e) {
  190. throw new \Exception($e->getHint());
  191. }
  192. }
  193. /**
  194. * Check for generic requirements before creating a share
  195. *
  196. * @param IShare $share
  197. * @throws \InvalidArgumentException
  198. * @throws GenericShareException
  199. *
  200. * @suppress PhanUndeclaredClassMethod
  201. */
  202. protected function generalCreateChecks(IShare $share) {
  203. if ($share->getShareType() === IShare::TYPE_USER) {
  204. // We expect a valid user as sharedWith for user shares
  205. if (!$this->userManager->userExists($share->getSharedWith())) {
  206. throw new \InvalidArgumentException('SharedWith is not a valid user');
  207. }
  208. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  209. // We expect a valid group as sharedWith for group shares
  210. if (!$this->groupManager->groupExists($share->getSharedWith())) {
  211. throw new \InvalidArgumentException('SharedWith is not a valid group');
  212. }
  213. } elseif ($share->getShareType() === IShare::TYPE_LINK) {
  214. // No check for TYPE_EMAIL here as we have a recipient for them
  215. if ($share->getSharedWith() !== null) {
  216. throw new \InvalidArgumentException('SharedWith should be empty');
  217. }
  218. } elseif ($share->getShareType() === IShare::TYPE_EMAIL) {
  219. if ($share->getSharedWith() === null) {
  220. throw new \InvalidArgumentException('SharedWith should not be empty');
  221. }
  222. } elseif ($share->getShareType() === IShare::TYPE_REMOTE) {
  223. if ($share->getSharedWith() === null) {
  224. throw new \InvalidArgumentException('SharedWith should not be empty');
  225. }
  226. } elseif ($share->getShareType() === IShare::TYPE_REMOTE_GROUP) {
  227. if ($share->getSharedWith() === null) {
  228. throw new \InvalidArgumentException('SharedWith should not be empty');
  229. }
  230. } elseif ($share->getShareType() === IShare::TYPE_CIRCLE) {
  231. $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
  232. if ($circle === null) {
  233. throw new \InvalidArgumentException('SharedWith is not a valid circle');
  234. }
  235. } elseif ($share->getShareType() === IShare::TYPE_ROOM) {
  236. } elseif ($share->getShareType() === IShare::TYPE_DECK) {
  237. } elseif ($share->getShareType() === IShare::TYPE_SCIENCEMESH) {
  238. } else {
  239. // We cannot handle other types yet
  240. throw new \InvalidArgumentException('unknown share type');
  241. }
  242. // Verify the initiator of the share is set
  243. if ($share->getSharedBy() === null) {
  244. throw new \InvalidArgumentException('SharedBy should be set');
  245. }
  246. // Cannot share with yourself
  247. if ($share->getShareType() === IShare::TYPE_USER &&
  248. $share->getSharedWith() === $share->getSharedBy()) {
  249. throw new \InvalidArgumentException('Cannot share with yourself');
  250. }
  251. // The path should be set
  252. if ($share->getNode() === null) {
  253. throw new \InvalidArgumentException('Path should be set');
  254. }
  255. // And it should be a file or a folder
  256. if (!($share->getNode() instanceof \OCP\Files\File) &&
  257. !($share->getNode() instanceof \OCP\Files\Folder)) {
  258. throw new \InvalidArgumentException('Path should be either a file or a folder');
  259. }
  260. // And you cannot share your rootfolder
  261. if ($this->userManager->userExists($share->getSharedBy())) {
  262. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  263. } else {
  264. $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  265. }
  266. if ($userFolder->getId() === $share->getNode()->getId()) {
  267. throw new \InvalidArgumentException('You cannot share your root folder');
  268. }
  269. // Check if we actually have share permissions
  270. if (!$share->getNode()->isShareable()) {
  271. $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getName()]);
  272. throw new GenericShareException($message_t, $message_t, 404);
  273. }
  274. // Permissions should be set
  275. if ($share->getPermissions() === null) {
  276. throw new \InvalidArgumentException('A share requires permissions');
  277. }
  278. $isFederatedShare = $share->getNode()->getStorage()->instanceOfStorage('\OCA\Files_Sharing\External\Storage');
  279. $permissions = 0;
  280. if (!$isFederatedShare && $share->getNode()->getOwner() && $share->getNode()->getOwner()->getUID() !== $share->getSharedBy()) {
  281. $userMounts = array_filter($userFolder->getById($share->getNode()->getId()), function ($mount) {
  282. // We need to filter since there might be other mountpoints that contain the file
  283. // e.g. if the user has access to the same external storage that the file is originating from
  284. return $mount->getStorage()->instanceOfStorage(ISharedStorage::class);
  285. });
  286. $userMount = array_shift($userMounts);
  287. if ($userMount === null) {
  288. throw new GenericShareException('Could not get proper share mount for ' . $share->getNode()->getId() . '. Failing since else the next calls are called with null');
  289. }
  290. $mount = $userMount->getMountPoint();
  291. // When it's a reshare use the parent share permissions as maximum
  292. $userMountPointId = $mount->getStorageRootId();
  293. $userMountPoints = $userFolder->getById($userMountPointId);
  294. $userMountPoint = array_shift($userMountPoints);
  295. if ($userMountPoint === null) {
  296. throw new GenericShareException('Could not get proper user mount for ' . $userMountPointId . '. Failing since else the next calls are called with null');
  297. }
  298. /* Check if this is an incoming share */
  299. $incomingShares = $this->getSharedWith($share->getSharedBy(), IShare::TYPE_USER, $userMountPoint, -1, 0);
  300. $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), IShare::TYPE_GROUP, $userMountPoint, -1, 0));
  301. $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), IShare::TYPE_CIRCLE, $userMountPoint, -1, 0));
  302. $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), IShare::TYPE_ROOM, $userMountPoint, -1, 0));
  303. /** @var IShare[] $incomingShares */
  304. if (!empty($incomingShares)) {
  305. foreach ($incomingShares as $incomingShare) {
  306. $permissions |= $incomingShare->getPermissions();
  307. }
  308. }
  309. } else {
  310. /*
  311. * Quick fix for #23536
  312. * Non moveable mount points do not have update and delete permissions
  313. * while we 'most likely' do have that on the storage.
  314. */
  315. $permissions = $share->getNode()->getPermissions();
  316. if (!($share->getNode()->getMountPoint() instanceof MoveableMount)) {
  317. $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
  318. }
  319. }
  320. // Check that we do not share with more permissions than we have
  321. if ($share->getPermissions() & ~$permissions) {
  322. $path = $userFolder->getRelativePath($share->getNode()->getPath());
  323. $message_t = $this->l->t('Cannot increase permissions of %s', [$path]);
  324. throw new GenericShareException($message_t, $message_t, 404);
  325. }
  326. // Check that read permissions are always set
  327. // Link shares are allowed to have no read permissions to allow upload to hidden folders
  328. $noReadPermissionRequired = $share->getShareType() === IShare::TYPE_LINK
  329. || $share->getShareType() === IShare::TYPE_EMAIL;
  330. if (!$noReadPermissionRequired &&
  331. ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
  332. throw new \InvalidArgumentException('Shares need at least read permissions');
  333. }
  334. if ($share->getNode() instanceof \OCP\Files\File) {
  335. if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
  336. $message_t = $this->l->t('Files cannot be shared with delete permissions');
  337. throw new GenericShareException($message_t);
  338. }
  339. if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
  340. $message_t = $this->l->t('Files cannot be shared with create permissions');
  341. throw new GenericShareException($message_t);
  342. }
  343. }
  344. }
  345. /**
  346. * Validate if the expiration date fits the system settings
  347. *
  348. * @param IShare $share The share to validate the expiration date of
  349. * @return IShare The modified share object
  350. * @throws GenericShareException
  351. * @throws \InvalidArgumentException
  352. * @throws \Exception
  353. */
  354. protected function validateExpirationDateInternal(IShare $share) {
  355. $isRemote = $share->getShareType() === IShare::TYPE_REMOTE || $share->getShareType() === IShare::TYPE_REMOTE_GROUP;
  356. $expirationDate = $share->getExpirationDate();
  357. if ($expirationDate !== null) {
  358. //Make sure the expiration date is a date
  359. $expirationDate->setTime(0, 0, 0);
  360. $date = new \DateTime();
  361. $date->setTime(0, 0, 0);
  362. if ($date >= $expirationDate) {
  363. $message = $this->l->t('Expiration date is in the past');
  364. throw new GenericShareException($message, $message, 404);
  365. }
  366. }
  367. // If expiredate is empty set a default one if there is a default
  368. $fullId = null;
  369. try {
  370. $fullId = $share->getFullId();
  371. } catch (\UnexpectedValueException $e) {
  372. // This is a new share
  373. }
  374. if ($isRemote) {
  375. $defaultExpireDate = $this->shareApiRemoteDefaultExpireDate();
  376. $defaultExpireDays = $this->shareApiRemoteDefaultExpireDays();
  377. $configProp = 'remote_defaultExpDays';
  378. $isEnforced = $this->shareApiRemoteDefaultExpireDateEnforced();
  379. } else {
  380. $defaultExpireDate = $this->shareApiInternalDefaultExpireDate();
  381. $defaultExpireDays = $this->shareApiInternalDefaultExpireDays();
  382. $configProp = 'internal_defaultExpDays';
  383. $isEnforced = $this->shareApiInternalDefaultExpireDateEnforced();
  384. }
  385. if ($fullId === null && $expirationDate === null && $defaultExpireDate) {
  386. $expirationDate = new \DateTime();
  387. $expirationDate->setTime(0, 0, 0);
  388. $days = (int)$this->config->getAppValue('core', $configProp, (string)$defaultExpireDays);
  389. if ($days > $defaultExpireDays) {
  390. $days = $defaultExpireDays;
  391. }
  392. $expirationDate->add(new \DateInterval('P' . $days . 'D'));
  393. }
  394. // If we enforce the expiration date check that is does not exceed
  395. if ($isEnforced) {
  396. if ($expirationDate === null) {
  397. throw new \InvalidArgumentException('Expiration date is enforced');
  398. }
  399. $date = new \DateTime();
  400. $date->setTime(0, 0, 0);
  401. $date->add(new \DateInterval('P' . $defaultExpireDays . 'D'));
  402. if ($date < $expirationDate) {
  403. $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);
  404. throw new GenericShareException($message, $message, 404);
  405. }
  406. }
  407. $accepted = true;
  408. $message = '';
  409. \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
  410. 'expirationDate' => &$expirationDate,
  411. 'accepted' => &$accepted,
  412. 'message' => &$message,
  413. 'passwordSet' => $share->getPassword() !== null,
  414. ]);
  415. if (!$accepted) {
  416. throw new \Exception($message);
  417. }
  418. $share->setExpirationDate($expirationDate);
  419. return $share;
  420. }
  421. /**
  422. * Validate if the expiration date fits the system settings
  423. *
  424. * @param IShare $share The share to validate the expiration date of
  425. * @return IShare The modified share object
  426. * @throws GenericShareException
  427. * @throws \InvalidArgumentException
  428. * @throws \Exception
  429. */
  430. protected function validateExpirationDateLink(IShare $share) {
  431. $expirationDate = $share->getExpirationDate();
  432. if ($expirationDate !== null) {
  433. //Make sure the expiration date is a date
  434. $expirationDate->setTime(0, 0, 0);
  435. $date = new \DateTime();
  436. $date->setTime(0, 0, 0);
  437. if ($date >= $expirationDate) {
  438. $message = $this->l->t('Expiration date is in the past');
  439. throw new GenericShareException($message, $message, 404);
  440. }
  441. }
  442. // If expiredate is empty set a default one if there is a default
  443. $fullId = null;
  444. try {
  445. $fullId = $share->getFullId();
  446. } catch (\UnexpectedValueException $e) {
  447. // This is a new share
  448. }
  449. if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
  450. $expirationDate = new \DateTime();
  451. $expirationDate->setTime(0, 0, 0);
  452. $days = (int)$this->config->getAppValue('core', 'link_defaultExpDays', (string)$this->shareApiLinkDefaultExpireDays());
  453. if ($days > $this->shareApiLinkDefaultExpireDays()) {
  454. $days = $this->shareApiLinkDefaultExpireDays();
  455. }
  456. $expirationDate->add(new \DateInterval('P' . $days . 'D'));
  457. }
  458. // If we enforce the expiration date check that is does not exceed
  459. if ($this->shareApiLinkDefaultExpireDateEnforced()) {
  460. if ($expirationDate === null) {
  461. throw new \InvalidArgumentException('Expiration date is enforced');
  462. }
  463. $date = new \DateTime();
  464. $date->setTime(0, 0, 0);
  465. $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
  466. if ($date < $expirationDate) {
  467. $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());
  468. throw new GenericShareException($message, $message, 404);
  469. }
  470. }
  471. $accepted = true;
  472. $message = '';
  473. \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
  474. 'expirationDate' => &$expirationDate,
  475. 'accepted' => &$accepted,
  476. 'message' => &$message,
  477. 'passwordSet' => $share->getPassword() !== null,
  478. ]);
  479. if (!$accepted) {
  480. throw new \Exception($message);
  481. }
  482. $share->setExpirationDate($expirationDate);
  483. return $share;
  484. }
  485. /**
  486. * Check for pre share requirements for user shares
  487. *
  488. * @param IShare $share
  489. * @throws \Exception
  490. */
  491. protected function userCreateChecks(IShare $share) {
  492. // Check if we can share with group members only
  493. if ($this->shareWithGroupMembersOnly()) {
  494. $sharedBy = $this->userManager->get($share->getSharedBy());
  495. $sharedWith = $this->userManager->get($share->getSharedWith());
  496. // Verify we can share with this user
  497. $groups = array_intersect(
  498. $this->groupManager->getUserGroupIds($sharedBy),
  499. $this->groupManager->getUserGroupIds($sharedWith)
  500. );
  501. if (empty($groups)) {
  502. $message_t = $this->l->t('Sharing is only allowed with group members');
  503. throw new \Exception($message_t);
  504. }
  505. }
  506. /*
  507. * TODO: Could be costly, fix
  508. *
  509. * Also this is not what we want in the future.. then we want to squash identical shares.
  510. */
  511. $provider = $this->factory->getProviderForType(IShare::TYPE_USER);
  512. $existingShares = $provider->getSharesByPath($share->getNode());
  513. foreach ($existingShares as $existingShare) {
  514. // Ignore if it is the same share
  515. try {
  516. if ($existingShare->getFullId() === $share->getFullId()) {
  517. continue;
  518. }
  519. } catch (\UnexpectedValueException $e) {
  520. //Shares are not identical
  521. }
  522. // Identical share already exists
  523. if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
  524. $message = $this->l->t('Sharing %s failed, because this item is already shared with user %s', [$share->getNode()->getName(), $share->getSharedWithDisplayName()]);
  525. throw new AlreadySharedException($message, $existingShare);
  526. }
  527. // The share is already shared with this user via a group share
  528. if ($existingShare->getShareType() === IShare::TYPE_GROUP) {
  529. $group = $this->groupManager->get($existingShare->getSharedWith());
  530. if (!is_null($group)) {
  531. $user = $this->userManager->get($share->getSharedWith());
  532. if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
  533. $message = $this->l->t('Sharing %s failed, because this item is already shared with user %s', [$share->getNode()->getName(), $share->getSharedWithDisplayName()]);
  534. throw new AlreadySharedException($message, $existingShare);
  535. }
  536. }
  537. }
  538. }
  539. }
  540. /**
  541. * Check for pre share requirements for group shares
  542. *
  543. * @param IShare $share
  544. * @throws \Exception
  545. */
  546. protected function groupCreateChecks(IShare $share) {
  547. // Verify group shares are allowed
  548. if (!$this->allowGroupSharing()) {
  549. throw new \Exception('Group sharing is now allowed');
  550. }
  551. // Verify if the user can share with this group
  552. if ($this->shareWithGroupMembersOnly()) {
  553. $sharedBy = $this->userManager->get($share->getSharedBy());
  554. $sharedWith = $this->groupManager->get($share->getSharedWith());
  555. if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
  556. throw new \Exception('Sharing is only allowed within your own groups');
  557. }
  558. }
  559. /*
  560. * TODO: Could be costly, fix
  561. *
  562. * Also this is not what we want in the future.. then we want to squash identical shares.
  563. */
  564. $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
  565. $existingShares = $provider->getSharesByPath($share->getNode());
  566. foreach ($existingShares as $existingShare) {
  567. try {
  568. if ($existingShare->getFullId() === $share->getFullId()) {
  569. continue;
  570. }
  571. } catch (\UnexpectedValueException $e) {
  572. //It is a new share so just continue
  573. }
  574. if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
  575. throw new AlreadySharedException('Path is already shared with this group', $existingShare);
  576. }
  577. }
  578. }
  579. /**
  580. * Check for pre share requirements for link shares
  581. *
  582. * @param IShare $share
  583. * @throws \Exception
  584. */
  585. protected function linkCreateChecks(IShare $share) {
  586. // Are link shares allowed?
  587. if (!$this->shareApiAllowLinks()) {
  588. throw new \Exception('Link sharing is not allowed');
  589. }
  590. // Check if public upload is allowed
  591. if ($share->getNodeType() === 'folder' && !$this->shareApiLinkAllowPublicUpload() &&
  592. ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
  593. throw new \InvalidArgumentException('Public upload is not allowed');
  594. }
  595. }
  596. /**
  597. * To make sure we don't get invisible link shares we set the parent
  598. * of a link if it is a reshare. This is a quick word around
  599. * until we can properly display multiple link shares in the UI
  600. *
  601. * See: https://github.com/owncloud/core/issues/22295
  602. *
  603. * FIXME: Remove once multiple link shares can be properly displayed
  604. *
  605. * @param IShare $share
  606. */
  607. protected function setLinkParent(IShare $share) {
  608. // No sense in checking if the method is not there.
  609. if (method_exists($share, 'setParent')) {
  610. $storage = $share->getNode()->getStorage();
  611. if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
  612. /** @var \OCA\Files_Sharing\SharedStorage $storage */
  613. $share->setParent($storage->getShareId());
  614. }
  615. }
  616. }
  617. /**
  618. * @param File|Folder $path
  619. */
  620. protected function pathCreateChecks($path) {
  621. // Make sure that we do not share a path that contains a shared mountpoint
  622. if ($path instanceof \OCP\Files\Folder) {
  623. $mounts = $this->mountManager->findIn($path->getPath());
  624. foreach ($mounts as $mount) {
  625. if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
  626. throw new \InvalidArgumentException('Path contains files shared with you');
  627. }
  628. }
  629. }
  630. }
  631. /**
  632. * Check if the user that is sharing can actually share
  633. *
  634. * @param IShare $share
  635. * @throws \Exception
  636. */
  637. protected function canShare(IShare $share) {
  638. if (!$this->shareApiEnabled()) {
  639. throw new \Exception('Sharing is disabled');
  640. }
  641. if ($this->sharingDisabledForUser($share->getSharedBy())) {
  642. throw new \Exception('Sharing is disabled for you');
  643. }
  644. }
  645. /**
  646. * Share a path
  647. *
  648. * @param IShare $share
  649. * @return IShare The share object
  650. * @throws \Exception
  651. *
  652. * TODO: handle link share permissions or check them
  653. */
  654. public function createShare(IShare $share) {
  655. $this->canShare($share);
  656. $this->generalCreateChecks($share);
  657. // Verify if there are any issues with the path
  658. $this->pathCreateChecks($share->getNode());
  659. /*
  660. * On creation of a share the owner is always the owner of the path
  661. * Except for mounted federated shares.
  662. */
  663. $storage = $share->getNode()->getStorage();
  664. if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
  665. $parent = $share->getNode()->getParent();
  666. while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
  667. $parent = $parent->getParent();
  668. }
  669. $share->setShareOwner($parent->getOwner()->getUID());
  670. } else {
  671. if ($share->getNode()->getOwner()) {
  672. $share->setShareOwner($share->getNode()->getOwner()->getUID());
  673. } else {
  674. $share->setShareOwner($share->getSharedBy());
  675. }
  676. }
  677. try {
  678. // Verify share type
  679. if ($share->getShareType() === IShare::TYPE_USER) {
  680. $this->userCreateChecks($share);
  681. // Verify the expiration date
  682. $share = $this->validateExpirationDateInternal($share);
  683. } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
  684. $this->groupCreateChecks($share);
  685. // Verify the expiration date
  686. $share = $this->validateExpirationDateInternal($share);
  687. } elseif ($share->getShareType() === IShare::TYPE_REMOTE || $share->getShareType() === IShare::TYPE_REMOTE_GROUP) {
  688. //Verify the expiration date
  689. $share = $this->validateExpirationDateInternal($share);
  690. } elseif ($share->getShareType() === IShare::TYPE_LINK
  691. || $share->getShareType() === IShare::TYPE_EMAIL) {
  692. $this->linkCreateChecks($share);
  693. $this->setLinkParent($share);
  694. // For now ignore a set token.
  695. $share->setToken(
  696. $this->secureRandom->generate(
  697. \OC\Share\Constants::TOKEN_LENGTH,
  698. \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
  699. )
  700. );
  701. // Verify the expiration date
  702. $share = $this->validateExpirationDateLink($share);
  703. // Verify the password
  704. $this->verifyPassword($share->getPassword());
  705. // If a password is set. Hash it!
  706. if ($share->getShareType() === IShare::TYPE_LINK
  707. && $share->getPassword() !== null) {
  708. $share->setPassword($this->hasher->hash($share->getPassword()));
  709. }
  710. }
  711. // Cannot share with the owner
  712. if ($share->getShareType() === IShare::TYPE_USER &&
  713. $share->getSharedWith() === $share->getShareOwner()) {
  714. throw new \InvalidArgumentException('Cannot share with the share owner');
  715. }
  716. // Generate the target
  717. $defaultShareFolder = $this->config->getSystemValue('share_folder', '/');
  718. $allowCustomShareFolder = $this->config->getSystemValueBool('sharing.allow_custom_share_folder', true);
  719. if ($allowCustomShareFolder) {
  720. $shareFolder = $this->config->getUserValue($share->getSharedWith(), Application::APP_ID, 'share_folder', $defaultShareFolder);
  721. } else {
  722. $shareFolder = $defaultShareFolder;
  723. }
  724. $target = $shareFolder . '/' . $share->getNode()->getName();
  725. $target = \OC\Files\Filesystem::normalizePath($target);
  726. $share->setTarget($target);
  727. // Pre share event
  728. $event = new Share\Events\BeforeShareCreatedEvent($share);
  729. $this->dispatcher->dispatchTyped($event);
  730. if ($event->isPropagationStopped() && $event->getError()) {
  731. throw new \Exception($event->getError());
  732. }
  733. $oldShare = $share;
  734. $provider = $this->factory->getProviderForType($share->getShareType());
  735. $share = $provider->create($share);
  736. // Reuse the node we already have
  737. $share->setNode($oldShare->getNode());
  738. // Reset the target if it is null for the new share
  739. if ($share->getTarget() === '') {
  740. $share->setTarget($target);
  741. }
  742. } catch (AlreadySharedException $e) {
  743. // if a share for the same target already exists, dont create a new one, but do trigger the hooks and notifications again
  744. $oldShare = $share;
  745. // Reuse the node we already have
  746. $share = $e->getExistingShare();
  747. $share->setNode($oldShare->getNode());
  748. }
  749. // Post share event
  750. $this->dispatcher->dispatchTyped(new 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 ShareAcceptedEvent($share);
  1003. $this->dispatcher->dispatchTyped($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->getSystemValueBool('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. $this->dispatcher->dispatchTyped(new BeforeShareDeletedEvent($child));
  1076. $deletedChildren = $this->deleteChildren($child);
  1077. $deletedShares = array_merge($deletedShares, $deletedChildren);
  1078. $provider->delete($child);
  1079. $this->dispatcher->dispatchTyped(new ShareDeletedEvent($child));
  1080. $deletedShares[] = $child;
  1081. }
  1082. return $deletedShares;
  1083. }
  1084. /**
  1085. * Delete a share
  1086. *
  1087. * @param IShare $share
  1088. * @throws ShareNotFound
  1089. * @throws \InvalidArgumentException
  1090. */
  1091. public function deleteShare(IShare $share) {
  1092. try {
  1093. $share->getFullId();
  1094. } catch (\UnexpectedValueException $e) {
  1095. throw new \InvalidArgumentException('Share does not have a full id');
  1096. }
  1097. $this->dispatcher->dispatchTyped(new BeforeShareDeletedEvent($share));
  1098. // Get all children and delete them as well
  1099. $this->deleteChildren($share);
  1100. // Do the actual delete
  1101. $provider = $this->factory->getProviderForType($share->getShareType());
  1102. $provider->delete($share);
  1103. $this->dispatcher->dispatchTyped(new ShareDeletedEvent($share));
  1104. }
  1105. /**
  1106. * Unshare a file as the recipient.
  1107. * This can be different from a regular delete for example when one of
  1108. * the users in a groups deletes that share. But the provider should
  1109. * handle this.
  1110. *
  1111. * @param IShare $share
  1112. * @param string $recipientId
  1113. */
  1114. public function deleteFromSelf(IShare $share, $recipientId) {
  1115. [$providerId,] = $this->splitFullId($share->getFullId());
  1116. $provider = $this->factory->getProvider($providerId);
  1117. $provider->deleteFromSelf($share, $recipientId);
  1118. $event = new ShareDeletedFromSelfEvent($share);
  1119. $this->dispatcher->dispatchTyped($event);
  1120. }
  1121. public function restoreShare(IShare $share, string $recipientId): IShare {
  1122. [$providerId,] = $this->splitFullId($share->getFullId());
  1123. $provider = $this->factory->getProvider($providerId);
  1124. return $provider->restore($share, $recipientId);
  1125. }
  1126. /**
  1127. * @inheritdoc
  1128. */
  1129. public function moveShare(IShare $share, $recipientId) {
  1130. if ($share->getShareType() === IShare::TYPE_LINK
  1131. || $share->getShareType() === IShare::TYPE_EMAIL) {
  1132. throw new \InvalidArgumentException('Cannot change target of link share');
  1133. }
  1134. if ($share->getShareType() === IShare::TYPE_USER && $share->getSharedWith() !== $recipientId) {
  1135. throw new \InvalidArgumentException('Invalid recipient');
  1136. }
  1137. if ($share->getShareType() === IShare::TYPE_GROUP) {
  1138. $sharedWith = $this->groupManager->get($share->getSharedWith());
  1139. if (is_null($sharedWith)) {
  1140. throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
  1141. }
  1142. $recipient = $this->userManager->get($recipientId);
  1143. if (!$sharedWith->inGroup($recipient)) {
  1144. throw new \InvalidArgumentException('Invalid recipient');
  1145. }
  1146. }
  1147. [$providerId,] = $this->splitFullId($share->getFullId());
  1148. $provider = $this->factory->getProvider($providerId);
  1149. return $provider->move($share, $recipientId);
  1150. }
  1151. public function getSharesInFolder($userId, Folder $node, $reshares = false, $shallow = true) {
  1152. $providers = $this->factory->getAllProviders();
  1153. return array_reduce($providers, function ($shares, IShareProvider $provider) use ($userId, $node, $reshares, $shallow) {
  1154. $newShares = $provider->getSharesInFolder($userId, $node, $reshares, $shallow);
  1155. foreach ($newShares as $fid => $data) {
  1156. if (!isset($shares[$fid])) {
  1157. $shares[$fid] = [];
  1158. }
  1159. $shares[$fid] = array_merge($shares[$fid], $data);
  1160. }
  1161. return $shares;
  1162. }, []);
  1163. }
  1164. /**
  1165. * @inheritdoc
  1166. */
  1167. public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
  1168. if ($path !== null &&
  1169. !($path instanceof \OCP\Files\File) &&
  1170. !($path instanceof \OCP\Files\Folder)) {
  1171. throw new \InvalidArgumentException('invalid path');
  1172. }
  1173. try {
  1174. $provider = $this->factory->getProviderForType($shareType);
  1175. } catch (ProviderException $e) {
  1176. return [];
  1177. }
  1178. $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
  1179. /*
  1180. * Work around so we don't return expired shares but still follow
  1181. * proper pagination.
  1182. */
  1183. $shares2 = [];
  1184. while (true) {
  1185. $added = 0;
  1186. foreach ($shares as $share) {
  1187. try {
  1188. $this->checkShare($share);
  1189. } catch (ShareNotFound $e) {
  1190. //Ignore since this basically means the share is deleted
  1191. continue;
  1192. }
  1193. $added++;
  1194. $shares2[] = $share;
  1195. if (count($shares2) === $limit) {
  1196. break;
  1197. }
  1198. }
  1199. // If we did not fetch more shares than the limit then there are no more shares
  1200. if (count($shares) < $limit) {
  1201. break;
  1202. }
  1203. if (count($shares2) === $limit) {
  1204. break;
  1205. }
  1206. // If there was no limit on the select we are done
  1207. if ($limit === -1) {
  1208. break;
  1209. }
  1210. $offset += $added;
  1211. // Fetch again $limit shares
  1212. $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
  1213. // No more shares means we are done
  1214. if (empty($shares)) {
  1215. break;
  1216. }
  1217. }
  1218. $shares = $shares2;
  1219. return $shares;
  1220. }
  1221. /**
  1222. * @inheritdoc
  1223. */
  1224. public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
  1225. try {
  1226. $provider = $this->factory->getProviderForType($shareType);
  1227. } catch (ProviderException $e) {
  1228. return [];
  1229. }
  1230. $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
  1231. // remove all shares which are already expired
  1232. foreach ($shares as $key => $share) {
  1233. try {
  1234. $this->checkShare($share);
  1235. } catch (ShareNotFound $e) {
  1236. unset($shares[$key]);
  1237. }
  1238. }
  1239. return $shares;
  1240. }
  1241. /**
  1242. * @inheritdoc
  1243. */
  1244. public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
  1245. $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
  1246. // Only get deleted shares
  1247. $shares = array_filter($shares, function (IShare $share) {
  1248. return $share->getPermissions() === 0;
  1249. });
  1250. // Only get shares where the owner still exists
  1251. $shares = array_filter($shares, function (IShare $share) {
  1252. return $this->userManager->userExists($share->getShareOwner());
  1253. });
  1254. return $shares;
  1255. }
  1256. /**
  1257. * @inheritdoc
  1258. */
  1259. public function getShareById($id, $recipient = null) {
  1260. if ($id === null) {
  1261. throw new ShareNotFound();
  1262. }
  1263. [$providerId, $id] = $this->splitFullId($id);
  1264. try {
  1265. $provider = $this->factory->getProvider($providerId);
  1266. } catch (ProviderException $e) {
  1267. throw new ShareNotFound();
  1268. }
  1269. $share = $provider->getShareById($id, $recipient);
  1270. $this->checkShare($share);
  1271. return $share;
  1272. }
  1273. /**
  1274. * Get all the shares for a given path
  1275. *
  1276. * @param \OCP\Files\Node $path
  1277. * @param int $page
  1278. * @param int $perPage
  1279. *
  1280. * @return Share[]
  1281. */
  1282. public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
  1283. return [];
  1284. }
  1285. /**
  1286. * Get the share by token possible with password
  1287. *
  1288. * @param string $token
  1289. * @return IShare
  1290. *
  1291. * @throws ShareNotFound
  1292. */
  1293. public function getShareByToken($token) {
  1294. // tokens cannot be valid local user names
  1295. if ($this->userManager->userExists($token)) {
  1296. throw new ShareNotFound();
  1297. }
  1298. $share = null;
  1299. try {
  1300. if ($this->shareApiAllowLinks()) {
  1301. $provider = $this->factory->getProviderForType(IShare::TYPE_LINK);
  1302. $share = $provider->getShareByToken($token);
  1303. }
  1304. } catch (ProviderException $e) {
  1305. } catch (ShareNotFound $e) {
  1306. }
  1307. // If it is not a link share try to fetch a federated share by token
  1308. if ($share === null) {
  1309. try {
  1310. $provider = $this->factory->getProviderForType(IShare::TYPE_REMOTE);
  1311. $share = $provider->getShareByToken($token);
  1312. } catch (ProviderException $e) {
  1313. } catch (ShareNotFound $e) {
  1314. }
  1315. }
  1316. // If it is not a link share try to fetch a mail share by token
  1317. if ($share === null && $this->shareProviderExists(IShare::TYPE_EMAIL)) {
  1318. try {
  1319. $provider = $this->factory->getProviderForType(IShare::TYPE_EMAIL);
  1320. $share = $provider->getShareByToken($token);
  1321. } catch (ProviderException $e) {
  1322. } catch (ShareNotFound $e) {
  1323. }
  1324. }
  1325. if ($share === null && $this->shareProviderExists(IShare::TYPE_CIRCLE)) {
  1326. try {
  1327. $provider = $this->factory->getProviderForType(IShare::TYPE_CIRCLE);
  1328. $share = $provider->getShareByToken($token);
  1329. } catch (ProviderException $e) {
  1330. } catch (ShareNotFound $e) {
  1331. }
  1332. }
  1333. if ($share === null && $this->shareProviderExists(IShare::TYPE_ROOM)) {
  1334. try {
  1335. $provider = $this->factory->getProviderForType(IShare::TYPE_ROOM);
  1336. $share = $provider->getShareByToken($token);
  1337. } catch (ProviderException $e) {
  1338. } catch (ShareNotFound $e) {
  1339. }
  1340. }
  1341. if ($share === null) {
  1342. throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
  1343. }
  1344. $this->checkShare($share);
  1345. /*
  1346. * Reduce the permissions for link or email shares if public upload is not enabled
  1347. */
  1348. if (($share->getShareType() === IShare::TYPE_LINK || $share->getShareType() === IShare::TYPE_EMAIL)
  1349. && $share->getNodeType() === 'folder' && !$this->shareApiLinkAllowPublicUpload()) {
  1350. $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
  1351. }
  1352. return $share;
  1353. }
  1354. /**
  1355. * Check expire date and disabled owner
  1356. *
  1357. * @throws ShareNotFound
  1358. */
  1359. protected function checkShare(IShare $share): void {
  1360. if ($share->isExpired()) {
  1361. $this->deleteShare($share);
  1362. throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
  1363. }
  1364. if ($this->config->getAppValue('files_sharing', 'hide_disabled_user_shares', 'no') === 'yes') {
  1365. $uids = array_unique([$share->getShareOwner(),$share->getSharedBy()]);
  1366. foreach ($uids as $uid) {
  1367. $user = $this->userManager->get($uid);
  1368. if ($user?->isEnabled() === false) {
  1369. throw new ShareNotFound($this->l->t('The requested share comes from a disabled user'));
  1370. }
  1371. }
  1372. }
  1373. }
  1374. /**
  1375. * Verify the password of a public share
  1376. *
  1377. * @param IShare $share
  1378. * @param ?string $password
  1379. * @return bool
  1380. */
  1381. public function checkPassword(IShare $share, $password) {
  1382. $passwordProtected = $share->getShareType() !== IShare::TYPE_LINK
  1383. || $share->getShareType() !== IShare::TYPE_EMAIL
  1384. || $share->getShareType() !== IShare::TYPE_CIRCLE;
  1385. if (!$passwordProtected) {
  1386. //TODO maybe exception?
  1387. return false;
  1388. }
  1389. if ($password === null || $share->getPassword() === null) {
  1390. return false;
  1391. }
  1392. // Makes sure password hasn't expired
  1393. $expirationTime = $share->getPasswordExpirationTime();
  1394. if ($expirationTime !== null && $expirationTime < new \DateTime()) {
  1395. return false;
  1396. }
  1397. $newHash = '';
  1398. if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
  1399. return false;
  1400. }
  1401. if (!empty($newHash)) {
  1402. $share->setPassword($newHash);
  1403. $provider = $this->factory->getProviderForType($share->getShareType());
  1404. $provider->update($share);
  1405. }
  1406. return true;
  1407. }
  1408. /**
  1409. * @inheritdoc
  1410. */
  1411. public function userDeleted($uid) {
  1412. $types = [IShare::TYPE_USER, IShare::TYPE_GROUP, IShare::TYPE_LINK, IShare::TYPE_REMOTE, IShare::TYPE_EMAIL];
  1413. foreach ($types as $type) {
  1414. try {
  1415. $provider = $this->factory->getProviderForType($type);
  1416. } catch (ProviderException $e) {
  1417. continue;
  1418. }
  1419. $provider->userDeleted($uid, $type);
  1420. }
  1421. }
  1422. /**
  1423. * @inheritdoc
  1424. */
  1425. public function groupDeleted($gid) {
  1426. $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
  1427. $provider->groupDeleted($gid);
  1428. $excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
  1429. if ($excludedGroups === '') {
  1430. return;
  1431. }
  1432. $excludedGroups = json_decode($excludedGroups, true);
  1433. if (json_last_error() !== JSON_ERROR_NONE) {
  1434. return;
  1435. }
  1436. $excludedGroups = array_diff($excludedGroups, [$gid]);
  1437. $this->config->setAppValue('core', 'shareapi_exclude_groups_list', json_encode($excludedGroups));
  1438. }
  1439. /**
  1440. * @inheritdoc
  1441. */
  1442. public function userDeletedFromGroup($uid, $gid) {
  1443. $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
  1444. $provider->userDeletedFromGroup($uid, $gid);
  1445. }
  1446. /**
  1447. * Get access list to a path. This means
  1448. * all the users that can access a given path.
  1449. *
  1450. * Consider:
  1451. * -root
  1452. * |-folder1 (23)
  1453. * |-folder2 (32)
  1454. * |-fileA (42)
  1455. *
  1456. * fileA is shared with user1 and user1@server1
  1457. * folder2 is shared with group2 (user4 is a member of group2)
  1458. * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
  1459. *
  1460. * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
  1461. * [
  1462. * users => [
  1463. * 'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
  1464. * 'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
  1465. * 'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
  1466. * ],
  1467. * remote => [
  1468. * 'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
  1469. * 'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
  1470. * ],
  1471. * public => bool
  1472. * mail => bool
  1473. * ]
  1474. *
  1475. * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
  1476. * [
  1477. * users => ['user1', 'user2', 'user4'],
  1478. * remote => bool,
  1479. * public => bool
  1480. * mail => bool
  1481. * ]
  1482. *
  1483. * This is required for encryption/activity
  1484. *
  1485. * @param \OCP\Files\Node $path
  1486. * @param bool $recursive Should we check all parent folders as well
  1487. * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
  1488. * @return array
  1489. */
  1490. public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
  1491. $owner = $path->getOwner();
  1492. if ($owner === null) {
  1493. return [];
  1494. }
  1495. $owner = $owner->getUID();
  1496. if ($currentAccess) {
  1497. $al = ['users' => [], 'remote' => [], 'public' => false];
  1498. } else {
  1499. $al = ['users' => [], 'remote' => false, 'public' => false];
  1500. }
  1501. if (!$this->userManager->userExists($owner)) {
  1502. return $al;
  1503. }
  1504. //Get node for the owner and correct the owner in case of external storage
  1505. $userFolder = $this->rootFolder->getUserFolder($owner);
  1506. if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
  1507. $nodes = $userFolder->getById($path->getId());
  1508. $path = array_shift($nodes);
  1509. if ($path === null || $path->getOwner() === null) {
  1510. return [];
  1511. }
  1512. $owner = $path->getOwner()->getUID();
  1513. }
  1514. $providers = $this->factory->getAllProviders();
  1515. /** @var Node[] $nodes */
  1516. $nodes = [];
  1517. if ($currentAccess) {
  1518. $ownerPath = $path->getPath();
  1519. $ownerPath = explode('/', $ownerPath, 4);
  1520. if (count($ownerPath) < 4) {
  1521. $ownerPath = '';
  1522. } else {
  1523. $ownerPath = $ownerPath[3];
  1524. }
  1525. $al['users'][$owner] = [
  1526. 'node_id' => $path->getId(),
  1527. 'node_path' => '/' . $ownerPath,
  1528. ];
  1529. } else {
  1530. $al['users'][] = $owner;
  1531. }
  1532. // Collect all the shares
  1533. while ($path->getPath() !== $userFolder->getPath()) {
  1534. $nodes[] = $path;
  1535. if (!$recursive) {
  1536. break;
  1537. }
  1538. $path = $path->getParent();
  1539. }
  1540. foreach ($providers as $provider) {
  1541. $tmp = $provider->getAccessList($nodes, $currentAccess);
  1542. foreach ($tmp as $k => $v) {
  1543. if (isset($al[$k])) {
  1544. if (is_array($al[$k])) {
  1545. if ($currentAccess) {
  1546. $al[$k] += $v;
  1547. } else {
  1548. $al[$k] = array_merge($al[$k], $v);
  1549. $al[$k] = array_unique($al[$k]);
  1550. $al[$k] = array_values($al[$k]);
  1551. }
  1552. } else {
  1553. $al[$k] = $al[$k] || $v;
  1554. }
  1555. } else {
  1556. $al[$k] = $v;
  1557. }
  1558. }
  1559. }
  1560. return $al;
  1561. }
  1562. /**
  1563. * Create a new share
  1564. *
  1565. * @return IShare
  1566. */
  1567. public function newShare() {
  1568. return new \OC\Share20\Share($this->rootFolder, $this->userManager);
  1569. }
  1570. /**
  1571. * Is the share API enabled
  1572. *
  1573. * @return bool
  1574. */
  1575. public function shareApiEnabled() {
  1576. return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
  1577. }
  1578. /**
  1579. * Is public link sharing enabled
  1580. *
  1581. * @return bool
  1582. */
  1583. public function shareApiAllowLinks() {
  1584. if ($this->config->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
  1585. return false;
  1586. }
  1587. $user = $this->userSession->getUser();
  1588. if ($user) {
  1589. $excludedGroups = json_decode($this->config->getAppValue('core', 'shareapi_allow_links_exclude_groups', '[]'));
  1590. if ($excludedGroups) {
  1591. $userGroups = $this->groupManager->getUserGroupIds($user);
  1592. return !(bool)array_intersect($excludedGroups, $userGroups);
  1593. }
  1594. }
  1595. return true;
  1596. }
  1597. /**
  1598. * Is password on public link requires
  1599. *
  1600. * @param bool Check group membership exclusion
  1601. * @return bool
  1602. */
  1603. public function shareApiLinkEnforcePassword(bool $checkGroupMembership = true) {
  1604. $excludedGroups = $this->config->getAppValue('core', 'shareapi_enforce_links_password_excluded_groups', '');
  1605. if ($excludedGroups !== '' && $checkGroupMembership) {
  1606. $excludedGroups = json_decode($excludedGroups);
  1607. $user = $this->userSession->getUser();
  1608. if ($user) {
  1609. $userGroups = $this->groupManager->getUserGroupIds($user);
  1610. if ((bool)array_intersect($excludedGroups, $userGroups)) {
  1611. return false;
  1612. }
  1613. }
  1614. }
  1615. return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
  1616. }
  1617. /**
  1618. * Is default link expire date enabled
  1619. *
  1620. * @return bool
  1621. */
  1622. public function shareApiLinkDefaultExpireDate() {
  1623. return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
  1624. }
  1625. /**
  1626. * Is default link expire date enforced
  1627. *`
  1628. *
  1629. * @return bool
  1630. */
  1631. public function shareApiLinkDefaultExpireDateEnforced() {
  1632. return $this->shareApiLinkDefaultExpireDate() &&
  1633. $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
  1634. }
  1635. /**
  1636. * Number of default link expire days
  1637. *
  1638. * @return int
  1639. */
  1640. public function shareApiLinkDefaultExpireDays() {
  1641. return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
  1642. }
  1643. /**
  1644. * Is default internal expire date enabled
  1645. *
  1646. * @return bool
  1647. */
  1648. public function shareApiInternalDefaultExpireDate(): bool {
  1649. return $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
  1650. }
  1651. /**
  1652. * Is default remote expire date enabled
  1653. *
  1654. * @return bool
  1655. */
  1656. public function shareApiRemoteDefaultExpireDate(): bool {
  1657. return $this->config->getAppValue('core', 'shareapi_default_remote_expire_date', 'no') === 'yes';
  1658. }
  1659. /**
  1660. * Is default expire date enforced
  1661. *
  1662. * @return bool
  1663. */
  1664. public function shareApiInternalDefaultExpireDateEnforced(): bool {
  1665. return $this->shareApiInternalDefaultExpireDate() &&
  1666. $this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
  1667. }
  1668. /**
  1669. * Is default expire date enforced for remote shares
  1670. *
  1671. * @return bool
  1672. */
  1673. public function shareApiRemoteDefaultExpireDateEnforced(): bool {
  1674. return $this->shareApiRemoteDefaultExpireDate() &&
  1675. $this->config->getAppValue('core', 'shareapi_enforce_remote_expire_date', 'no') === 'yes';
  1676. }
  1677. /**
  1678. * Number of default expire days
  1679. *
  1680. * @return int
  1681. */
  1682. public function shareApiInternalDefaultExpireDays(): int {
  1683. return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
  1684. }
  1685. /**
  1686. * Number of default expire days for remote shares
  1687. *
  1688. * @return int
  1689. */
  1690. public function shareApiRemoteDefaultExpireDays(): int {
  1691. return (int)$this->config->getAppValue('core', 'shareapi_remote_expire_after_n_days', '7');
  1692. }
  1693. /**
  1694. * Allow public upload on link shares
  1695. *
  1696. * @return bool
  1697. */
  1698. public function shareApiLinkAllowPublicUpload() {
  1699. return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
  1700. }
  1701. /**
  1702. * check if user can only share with group members
  1703. *
  1704. * @return bool
  1705. */
  1706. public function shareWithGroupMembersOnly() {
  1707. return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
  1708. }
  1709. /**
  1710. * Check if users can share with groups
  1711. *
  1712. * @return bool
  1713. */
  1714. public function allowGroupSharing() {
  1715. return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
  1716. }
  1717. public function allowEnumeration(): bool {
  1718. return $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
  1719. }
  1720. public function limitEnumerationToGroups(): bool {
  1721. return $this->allowEnumeration() &&
  1722. $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
  1723. }
  1724. public function limitEnumerationToPhone(): bool {
  1725. return $this->allowEnumeration() &&
  1726. $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
  1727. }
  1728. public function allowEnumerationFullMatch(): bool {
  1729. return $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_full_match', 'yes') === 'yes';
  1730. }
  1731. public function matchEmail(): bool {
  1732. return $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_full_match_email', 'yes') === 'yes';
  1733. }
  1734. public function ignoreSecondDisplayName(): bool {
  1735. return $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_full_match_ignore_second_dn', 'no') === 'yes';
  1736. }
  1737. public function currentUserCanEnumerateTargetUser(?IUser $currentUser, IUser $targetUser): bool {
  1738. if ($this->allowEnumerationFullMatch()) {
  1739. return true;
  1740. }
  1741. if (!$this->allowEnumeration()) {
  1742. return false;
  1743. }
  1744. if (!$this->limitEnumerationToPhone() && !$this->limitEnumerationToGroups()) {
  1745. // Enumeration is enabled and not restricted: OK
  1746. return true;
  1747. }
  1748. if (!$currentUser instanceof IUser) {
  1749. // Enumeration restrictions require an account
  1750. return false;
  1751. }
  1752. // Enumeration is limited to phone match
  1753. if ($this->limitEnumerationToPhone() && $this->knownUserService->isKnownToUser($currentUser->getUID(), $targetUser->getUID())) {
  1754. return true;
  1755. }
  1756. // Enumeration is limited to groups
  1757. if ($this->limitEnumerationToGroups()) {
  1758. $currentUserGroupIds = $this->groupManager->getUserGroupIds($currentUser);
  1759. $targetUserGroupIds = $this->groupManager->getUserGroupIds($targetUser);
  1760. if (!empty(array_intersect($currentUserGroupIds, $targetUserGroupIds))) {
  1761. return true;
  1762. }
  1763. }
  1764. return false;
  1765. }
  1766. /**
  1767. * Copied from \OC_Util::isSharingDisabledForUser
  1768. *
  1769. * TODO: Deprecate function from OC_Util
  1770. *
  1771. * @param string $userId
  1772. * @return bool
  1773. */
  1774. public function sharingDisabledForUser($userId) {
  1775. return $this->shareDisableChecker->sharingDisabledForUser($userId);
  1776. }
  1777. /**
  1778. * @inheritdoc
  1779. */
  1780. public function outgoingServer2ServerSharesAllowed() {
  1781. return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
  1782. }
  1783. /**
  1784. * @inheritdoc
  1785. */
  1786. public function outgoingServer2ServerGroupSharesAllowed() {
  1787. return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
  1788. }
  1789. /**
  1790. * @inheritdoc
  1791. */
  1792. public function shareProviderExists($shareType) {
  1793. try {
  1794. $this->factory->getProviderForType($shareType);
  1795. } catch (ProviderException $e) {
  1796. return false;
  1797. }
  1798. return true;
  1799. }
  1800. public function registerShareProvider(string $shareProviderClass): void {
  1801. $this->factory->registerProvider($shareProviderClass);
  1802. }
  1803. public function getAllShares(): iterable {
  1804. $providers = $this->factory->getAllProviders();
  1805. foreach ($providers as $provider) {
  1806. yield from $provider->getAllShares();
  1807. }
  1808. }
  1809. }