You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Manager.php 66KB

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