Manager.php 63 KB

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