Manager.php 59 KB

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