Manager.php 63 KB

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