1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198 |
- <?php
- /**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Vincent Petry <pvince81@owncloud.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
- */
- namespace OC\Share20;
- use OC\Files\Mount\MoveableMount;
- use OC\HintException;
- use OCP\Files\IRootFolder;
- use OCP\Files\NotFoundException;
- use OCP\IUserManager;
- use OCP\Share\IManager;
- use OCP\Share\IProviderFactory;
- use OC\Share20\Exception\BackendError;
- use OCP\IConfig;
- use OCP\IL10N;
- use OCP\ILogger;
- use OCP\Security\ISecureRandom;
- use OCP\Security\IHasher;
- use OCP\Files\Mount\IMountManager;
- use OCP\IGroupManager;
- use OCP\Files\File;
- use OCP\Files\Folder;
- use OCP\Share\Exceptions\ShareNotFound;
- use OCP\Share\Exceptions\GenericShareException;
- use Symfony\Component\EventDispatcher\EventDispatcher;
- use Symfony\Component\EventDispatcher\GenericEvent;
- /**
- * This class is the communication hub for all sharing related operations.
- */
- class Manager implements IManager {
- /** @var IProviderFactory */
- private $factory;
- /** @var ILogger */
- private $logger;
- /** @var IConfig */
- private $config;
- /** @var ISecureRandom */
- private $secureRandom;
- /** @var IHasher */
- private $hasher;
- /** @var IMountManager */
- private $mountManager;
- /** @var IGroupManager */
- private $groupManager;
- /** @var IL10N */
- private $l;
- /** @var IUserManager */
- private $userManager;
- /** @var IRootFolder */
- private $rootFolder;
- /**
- * Manager constructor.
- *
- * @param ILogger $logger
- * @param IConfig $config
- * @param ISecureRandom $secureRandom
- * @param IHasher $hasher
- * @param IMountManager $mountManager
- * @param IGroupManager $groupManager
- * @param IL10N $l
- * @param IProviderFactory $factory
- * @param IUserManager $userManager
- * @param IRootFolder $rootFolder
- * @param EventDispatcher $eventDispatcher
- */
- public function __construct(
- ILogger $logger,
- IConfig $config,
- ISecureRandom $secureRandom,
- IHasher $hasher,
- IMountManager $mountManager,
- IGroupManager $groupManager,
- IL10N $l,
- IProviderFactory $factory,
- IUserManager $userManager,
- IRootFolder $rootFolder,
- EventDispatcher $eventDispatcher
- ) {
- $this->logger = $logger;
- $this->config = $config;
- $this->secureRandom = $secureRandom;
- $this->hasher = $hasher;
- $this->mountManager = $mountManager;
- $this->groupManager = $groupManager;
- $this->l = $l;
- $this->factory = $factory;
- $this->userManager = $userManager;
- $this->rootFolder = $rootFolder;
- $this->eventDispatcher = $eventDispatcher;
- }
- /**
- * Convert from a full share id to a tuple (providerId, shareId)
- *
- * @param string $id
- * @return string[]
- */
- private function splitFullId($id) {
- return explode(':', $id, 2);
- }
- /**
- * Verify if a password meets all requirements
- *
- * @param string $password
- * @throws \Exception
- */
- protected function verifyPassword($password) {
- if ($password === null) {
- // No password is set, check if this is allowed.
- if ($this->shareApiLinkEnforcePassword()) {
- throw new \InvalidArgumentException('Passwords are enforced for link shares');
- }
- return;
- }
- // Let others verify the password
- try {
- $event = new GenericEvent($password);
- $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
- } catch (HintException $e) {
- throw new \Exception($e->getHint());
- }
- }
- /**
- * Check for generic requirements before creating a share
- *
- * @param \OCP\Share\IShare $share
- * @throws \InvalidArgumentException
- * @throws GenericShareException
- */
- protected function generalCreateChecks(\OCP\Share\IShare $share) {
- if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
- // We expect a valid user as sharedWith for user shares
- if (!$this->userManager->userExists($share->getSharedWith())) {
- throw new \InvalidArgumentException('SharedWith is not a valid user');
- }
- } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
- // We expect a valid group as sharedWith for group shares
- if (!$this->groupManager->groupExists($share->getSharedWith())) {
- throw new \InvalidArgumentException('SharedWith is not a valid group');
- }
- } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
- if ($share->getSharedWith() !== null) {
- throw new \InvalidArgumentException('SharedWith should be empty');
- }
- } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
- if ($share->getSharedWith() === null) {
- throw new \InvalidArgumentException('SharedWith should not be empty');
- }
- } else {
- // We can't handle other types yet
- throw new \InvalidArgumentException('unkown share type');
- }
- // Verify the initiator of the share is set
- if ($share->getSharedBy() === null) {
- throw new \InvalidArgumentException('SharedBy should be set');
- }
- // Cannot share with yourself
- if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
- $share->getSharedWith() === $share->getSharedBy()) {
- throw new \InvalidArgumentException('Can\'t share with yourself');
- }
- // The path should be set
- if ($share->getNode() === null) {
- throw new \InvalidArgumentException('Path should be set');
- }
- // And it should be a file or a folder
- if (!($share->getNode() instanceof \OCP\Files\File) &&
- !($share->getNode() instanceof \OCP\Files\Folder)) {
- throw new \InvalidArgumentException('Path should be either a file or a folder');
- }
- // And you can't share your rootfolder
- if ($this->rootFolder->getUserFolder($share->getSharedBy())->getPath() === $share->getNode()->getPath()) {
- throw new \InvalidArgumentException('You can\'t share your root folder');
- }
- // Check if we actually have share permissions
- if (!$share->getNode()->isShareable()) {
- $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
- throw new GenericShareException($message_t, $message_t, 404);
- }
- // Permissions should be set
- if ($share->getPermissions() === null) {
- throw new \InvalidArgumentException('A share requires permissions');
- }
- /*
- * Quick fix for #23536
- * Non moveable mount points do not have update and delete permissions
- * while we 'most likely' do have that on the storage.
- */
- $permissions = $share->getNode()->getPermissions();
- $mount = $share->getNode()->getMountPoint();
- if (!($mount instanceof MoveableMount)) {
- $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
- }
- // Check that we do not share with more permissions than we have
- if ($share->getPermissions() & ~$permissions) {
- $message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
- throw new GenericShareException($message_t, $message_t, 404);
- }
- // Link shares are allowed to have no read permissions to allow upload to hidden folders
- if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK &&
- ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
- throw new \InvalidArgumentException('Shares need at least read permissions');
- }
- }
- /**
- * Validate if the expiration date fits the system settings
- *
- * @param \OCP\Share\IShare $share The share to validate the expiration date of
- * @return \OCP\Share\IShare The modified share object
- * @throws GenericShareException
- * @throws \InvalidArgumentException
- * @throws \Exception
- */
- protected function validateExpirationDate(\OCP\Share\IShare $share) {
- $expirationDate = $share->getExpirationDate();
- if ($expirationDate !== null) {
- //Make sure the expiration date is a date
- $expirationDate->setTime(0, 0, 0);
- $date = new \DateTime();
- $date->setTime(0, 0, 0);
- if ($date >= $expirationDate) {
- $message = $this->l->t('Expiration date is in the past');
- throw new GenericShareException($message, $message, 404);
- }
- }
- // If expiredate is empty set a default one if there is a default
- $fullId = null;
- try {
- $fullId = $share->getFullId();
- } catch (\UnexpectedValueException $e) {
- // This is a new share
- }
- if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
- $expirationDate = new \DateTime();
- $expirationDate->setTime(0,0,0);
- $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
- }
- // If we enforce the expiration date check that is does not exceed
- if ($this->shareApiLinkDefaultExpireDateEnforced()) {
- if ($expirationDate === null) {
- throw new \InvalidArgumentException('Expiration date is enforced');
- }
- $date = new \DateTime();
- $date->setTime(0, 0, 0);
- $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
- if ($date < $expirationDate) {
- $message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
- throw new GenericShareException($message, $message, 404);
- }
- }
- $accepted = true;
- $message = '';
- \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
- 'expirationDate' => &$expirationDate,
- 'accepted' => &$accepted,
- 'message' => &$message,
- 'passwordSet' => $share->getPassword() !== null,
- ]);
- if (!$accepted) {
- throw new \Exception($message);
- }
- $share->setExpirationDate($expirationDate);
- return $share;
- }
- /**
- * Check for pre share requirements for user shares
- *
- * @param \OCP\Share\IShare $share
- * @throws \Exception
- */
- protected function userCreateChecks(\OCP\Share\IShare $share) {
- // Check if we can share with group members only
- if ($this->shareWithGroupMembersOnly()) {
- $sharedBy = $this->userManager->get($share->getSharedBy());
- $sharedWith = $this->userManager->get($share->getSharedWith());
- // Verify we can share with this user
- $groups = array_intersect(
- $this->groupManager->getUserGroupIds($sharedBy),
- $this->groupManager->getUserGroupIds($sharedWith)
- );
- if (empty($groups)) {
- throw new \Exception('Only sharing with group members is allowed');
- }
- }
- /*
- * TODO: Could be costly, fix
- *
- * Also this is not what we want in the future.. then we want to squash identical shares.
- */
- $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
- $existingShares = $provider->getSharesByPath($share->getNode());
- foreach($existingShares as $existingShare) {
- // Ignore if it is the same share
- try {
- if ($existingShare->getFullId() === $share->getFullId()) {
- continue;
- }
- } catch (\UnexpectedValueException $e) {
- //Shares are not identical
- }
- // Identical share already existst
- if ($existingShare->getSharedWith() === $share->getSharedWith()) {
- throw new \Exception('Path already shared with this user');
- }
- // The share is already shared with this user via a group share
- if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
- $group = $this->groupManager->get($existingShare->getSharedWith());
- $user = $this->userManager->get($share->getSharedWith());
- if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
- throw new \Exception('Path already shared with this user');
- }
- }
- }
- }
- /**
- * Check for pre share requirements for group shares
- *
- * @param \OCP\Share\IShare $share
- * @throws \Exception
- */
- protected function groupCreateChecks(\OCP\Share\IShare $share) {
- // Verify group shares are allowed
- if (!$this->allowGroupSharing()) {
- throw new \Exception('Group sharing is now allowed');
- }
- // Verify if the user can share with this group
- if ($this->shareWithGroupMembersOnly()) {
- $sharedBy = $this->userManager->get($share->getSharedBy());
- $sharedWith = $this->groupManager->get($share->getSharedWith());
- if (!$sharedWith->inGroup($sharedBy)) {
- throw new \Exception('Only sharing within your own groups is allowed');
- }
- }
- /*
- * TODO: Could be costly, fix
- *
- * Also this is not what we want in the future.. then we want to squash identical shares.
- */
- $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
- $existingShares = $provider->getSharesByPath($share->getNode());
- foreach($existingShares as $existingShare) {
- try {
- if ($existingShare->getFullId() === $share->getFullId()) {
- continue;
- }
- } catch (\UnexpectedValueException $e) {
- //It is a new share so just continue
- }
- if ($existingShare->getSharedWith() === $share->getSharedWith()) {
- throw new \Exception('Path already shared with this group');
- }
- }
- }
- /**
- * Check for pre share requirements for link shares
- *
- * @param \OCP\Share\IShare $share
- * @throws \Exception
- */
- protected function linkCreateChecks(\OCP\Share\IShare $share) {
- // Are link shares allowed?
- if (!$this->shareApiAllowLinks()) {
- throw new \Exception('Link sharing not allowed');
- }
- // Link shares by definition can't have share permissions
- if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
- throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
- }
- // We don't allow deletion on link shares
- if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
- throw new \InvalidArgumentException('Link shares can\'t have delete permissions');
- }
- // Check if public upload is allowed
- if (!$this->shareApiLinkAllowPublicUpload() &&
- ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE))) {
- throw new \InvalidArgumentException('Public upload not allowed');
- }
- }
- /**
- * To make sure we don't get invisible link shares we set the parent
- * of a link if it is a reshare. This is a quick word around
- * until we can properly display multiple link shares in the UI
- *
- * See: https://github.com/owncloud/core/issues/22295
- *
- * FIXME: Remove once multiple link shares can be properly displayed
- *
- * @param \OCP\Share\IShare $share
- */
- protected function setLinkParent(\OCP\Share\IShare $share) {
- // No sense in checking if the method is not there.
- if (method_exists($share, 'setParent')) {
- $storage = $share->getNode()->getStorage();
- if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
- $share->setParent($storage->getShareId());
- }
- };
- }
- /**
- * @param File|Folder $path
- */
- protected function pathCreateChecks($path) {
- // Make sure that we do not share a path that contains a shared mountpoint
- if ($path instanceof \OCP\Files\Folder) {
- $mounts = $this->mountManager->findIn($path->getPath());
- foreach($mounts as $mount) {
- if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
- throw new \InvalidArgumentException('Path contains files shared with you');
- }
- }
- }
- }
- /**
- * Check if the user that is sharing can actually share
- *
- * @param \OCP\Share\IShare $share
- * @throws \Exception
- */
- protected function canShare(\OCP\Share\IShare $share) {
- if (!$this->shareApiEnabled()) {
- throw new \Exception('The share API is disabled');
- }
- if ($this->sharingDisabledForUser($share->getSharedBy())) {
- throw new \Exception('You are not allowed to share');
- }
- }
- /**
- * Share a path
- *
- * @param \OCP\Share\IShare $share
- * @return Share The share object
- * @throws \Exception
- *
- * TODO: handle link share permissions or check them
- */
- public function createShare(\OCP\Share\IShare $share) {
- $this->canShare($share);
- $this->generalCreateChecks($share);
- // Verify if there are any issues with the path
- $this->pathCreateChecks($share->getNode());
- /*
- * On creation of a share the owner is always the owner of the path
- * Except for mounted federated shares.
- */
- $storage = $share->getNode()->getStorage();
- if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
- $parent = $share->getNode()->getParent();
- while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
- $parent = $parent->getParent();
- }
- $share->setShareOwner($parent->getOwner()->getUID());
- } else {
- $share->setShareOwner($share->getNode()->getOwner()->getUID());
- }
- //Verify share type
- if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
- $this->userCreateChecks($share);
- } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
- $this->groupCreateChecks($share);
- } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
- $this->linkCreateChecks($share);
- $this->setLinkParent($share);
- /*
- * For now ignore a set token.
- */
- $share->setToken(
- $this->secureRandom->generate(
- \OC\Share\Constants::TOKEN_LENGTH,
- \OCP\Security\ISecureRandom::CHAR_LOWER.
- \OCP\Security\ISecureRandom::CHAR_UPPER.
- \OCP\Security\ISecureRandom::CHAR_DIGITS
- )
- );
- //Verify the expiration date
- $this->validateExpirationDate($share);
- //Verify the password
- $this->verifyPassword($share->getPassword());
- // If a password is set. Hash it!
- if ($share->getPassword() !== null) {
- $share->setPassword($this->hasher->hash($share->getPassword()));
- }
- }
- // Cannot share with the owner
- if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
- $share->getSharedWith() === $share->getShareOwner()) {
- throw new \InvalidArgumentException('Can\'t share with the share owner');
- }
- // Generate the target
- $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
- $target = \OC\Files\Filesystem::normalizePath($target);
- $share->setTarget($target);
- // Pre share hook
- $run = true;
- $error = '';
- $preHookData = [
- 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
- 'itemSource' => $share->getNode()->getId(),
- 'shareType' => $share->getShareType(),
- 'uidOwner' => $share->getSharedBy(),
- 'permissions' => $share->getPermissions(),
- 'fileSource' => $share->getNode()->getId(),
- 'expiration' => $share->getExpirationDate(),
- 'token' => $share->getToken(),
- 'itemTarget' => $share->getTarget(),
- 'shareWith' => $share->getSharedWith(),
- 'run' => &$run,
- 'error' => &$error,
- ];
- \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
- if ($run === false) {
- throw new \Exception($error);
- }
- $provider = $this->factory->getProviderForType($share->getShareType());
- $share = $provider->create($share);
- // Post share hook
- $postHookData = [
- 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
- 'itemSource' => $share->getNode()->getId(),
- 'shareType' => $share->getShareType(),
- 'uidOwner' => $share->getSharedBy(),
- 'permissions' => $share->getPermissions(),
- 'fileSource' => $share->getNode()->getId(),
- 'expiration' => $share->getExpirationDate(),
- 'token' => $share->getToken(),
- 'id' => $share->getId(),
- 'shareWith' => $share->getSharedWith(),
- 'itemTarget' => $share->getTarget(),
- 'fileTarget' => $share->getTarget(),
- ];
- \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
- return $share;
- }
- /**
- * Update a share
- *
- * @param \OCP\Share\IShare $share
- * @return \OCP\Share\IShare The share object
- * @throws \InvalidArgumentException
- */
- public function updateShare(\OCP\Share\IShare $share) {
- $expirationDateUpdated = false;
- $this->canShare($share);
- try {
- $originalShare = $this->getShareById($share->getFullId());
- } catch (\UnexpectedValueException $e) {
- throw new \InvalidArgumentException('Share does not have a full id');
- }
- // We can't change the share type!
- if ($share->getShareType() !== $originalShare->getShareType()) {
- throw new \InvalidArgumentException('Can\'t change share type');
- }
- // We can only change the recipient on user shares
- if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
- $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
- throw new \InvalidArgumentException('Can only update recipient on user shares');
- }
- // Cannot share with the owner
- if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
- $share->getSharedWith() === $share->getShareOwner()) {
- throw new \InvalidArgumentException('Can\'t share with the share owner');
- }
- $this->generalCreateChecks($share);
- if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
- $this->userCreateChecks($share);
- } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
- $this->groupCreateChecks($share);
- } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
- $this->linkCreateChecks($share);
- // Password updated.
- if ($share->getPassword() !== $originalShare->getPassword()) {
- //Verify the password
- $this->verifyPassword($share->getPassword());
- // If a password is set. Hash it!
- if ($share->getPassword() !== null) {
- $share->setPassword($this->hasher->hash($share->getPassword()));
- }
- }
- if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
- //Verify the expiration date
- $this->validateExpirationDate($share);
- $expirationDateUpdated = true;
- }
- }
- $this->pathCreateChecks($share->getNode());
- // Now update the share!
- $provider = $this->factory->getProviderForType($share->getShareType());
- $share = $provider->update($share);
- if ($expirationDateUpdated === true) {
- \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
- 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
- 'itemSource' => $share->getNode()->getId(),
- 'date' => $share->getExpirationDate(),
- 'uidOwner' => $share->getSharedBy(),
- ]);
- }
- if ($share->getPassword() !== $originalShare->getPassword()) {
- \OC_Hook::emit('OCP\Share', 'post_update_password', [
- 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
- 'itemSource' => $share->getNode()->getId(),
- 'uidOwner' => $share->getSharedBy(),
- 'token' => $share->getToken(),
- 'disabled' => is_null($share->getPassword()),
- ]);
- }
- if ($share->getPermissions() !== $originalShare->getPermissions()) {
- $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
- \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
- 'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
- 'itemSource' => $share->getNode()->getId(),
- 'shareType' => $share->getShareType(),
- 'shareWith' => $share->getSharedWith(),
- 'uidOwner' => $share->getSharedBy(),
- 'permissions' => $share->getPermissions(),
- 'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
- ));
- }
- return $share;
- }
- /**
- * Delete all the children of this share
- * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
- *
- * @param \OCP\Share\IShare $share
- * @return \OCP\Share\IShare[] List of deleted shares
- */
- protected function deleteChildren(\OCP\Share\IShare $share) {
- $deletedShares = [];
- $provider = $this->factory->getProviderForType($share->getShareType());
- foreach ($provider->getChildren($share) as $child) {
- $deletedChildren = $this->deleteChildren($child);
- $deletedShares = array_merge($deletedShares, $deletedChildren);
- $provider->delete($child);
- $deletedShares[] = $child;
- }
- return $deletedShares;
- }
- /**
- * Delete a share
- *
- * @param \OCP\Share\IShare $share
- * @throws ShareNotFound
- * @throws \InvalidArgumentException
- */
- public function deleteShare(\OCP\Share\IShare $share) {
- try {
- $share->getFullId();
- } catch (\UnexpectedValueException $e) {
- throw new \InvalidArgumentException('Share does not have a full id');
- }
- $formatHookParams = function(\OCP\Share\IShare $share) {
- // Prepare hook
- $shareType = $share->getShareType();
- $sharedWith = '';
- if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
- $sharedWith = $share->getSharedWith();
- } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
- $sharedWith = $share->getSharedWith();
- } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
- $sharedWith = $share->getSharedWith();
- }
- $hookParams = [
- 'id' => $share->getId(),
- 'itemType' => $share->getNodeType(),
- 'itemSource' => $share->getNodeId(),
- 'shareType' => $shareType,
- 'shareWith' => $sharedWith,
- 'itemparent' => method_exists($share, 'getParent') ? $share->getParent() : '',
- 'uidOwner' => $share->getSharedBy(),
- 'fileSource' => $share->getNodeId(),
- 'fileTarget' => $share->getTarget()
- ];
- return $hookParams;
- };
- $hookParams = $formatHookParams($share);
- // Emit pre-hook
- \OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
- // Get all children and delete them as well
- $deletedShares = $this->deleteChildren($share);
- // Do the actual delete
- $provider = $this->factory->getProviderForType($share->getShareType());
- $provider->delete($share);
- // All the deleted shares caused by this delete
- $deletedShares[] = $share;
- //Format hook info
- $formattedDeletedShares = array_map(function($share) use ($formatHookParams) {
- return $formatHookParams($share);
- }, $deletedShares);
- $hookParams['deletedShares'] = $formattedDeletedShares;
- // Emit post hook
- \OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
- }
- /**
- * Unshare a file as the recipient.
- * This can be different from a regular delete for example when one of
- * the users in a groups deletes that share. But the provider should
- * handle this.
- *
- * @param \OCP\Share\IShare $share
- * @param string $recipientId
- */
- public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
- list($providerId, ) = $this->splitFullId($share->getId());
- $provider = $this->factory->getProvider($providerId);
- $provider->deleteFromSelf($share, $recipientId);
- }
- /**
- * @inheritdoc
- */
- public function moveShare(\OCP\Share\IShare $share, $recipientId) {
- if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
- throw new \InvalidArgumentException('Can\'t change target of link share');
- }
- if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
- throw new \InvalidArgumentException('Invalid recipient');
- }
- if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
- $sharedWith = $this->groupManager->get($share->getSharedWith());
- $recipient = $this->userManager->get($recipientId);
- if (!$sharedWith->inGroup($recipient)) {
- throw new \InvalidArgumentException('Invalid recipient');
- }
- }
- list($providerId, ) = $this->splitFullId($share->getId());
- $provider = $this->factory->getProvider($providerId);
- $provider->move($share, $recipientId);
- }
- /**
- * Get shares shared by (initiated) by the provided user.
- *
- * @param string $userId
- * @param int $shareType
- * @param \OCP\Files\File|\OCP\Files\Folder $path
- * @param bool $reshares
- * @param int $limit The maximum number of returned results, -1 for all results
- * @param int $offset
- * @return \OCP\Share\IShare[]
- */
- public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
- if ($path !== null &&
- !($path instanceof \OCP\Files\File) &&
- !($path instanceof \OCP\Files\Folder)) {
- throw new \InvalidArgumentException('invalid path');
- }
- $provider = $this->factory->getProviderForType($shareType);
- $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
- /*
- * Work around so we don't return expired shares but still follow
- * proper pagination.
- */
- if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
- $shares2 = [];
- $today = new \DateTime();
- while(true) {
- $added = 0;
- foreach ($shares as $share) {
- // Check if the share is expired and if so delete it
- if ($share->getExpirationDate() !== null &&
- $share->getExpirationDate() <= $today
- ) {
- try {
- $this->deleteShare($share);
- } catch (NotFoundException $e) {
- //Ignore since this basically means the share is deleted
- }
- continue;
- }
- $added++;
- $shares2[] = $share;
- if (count($shares2) === $limit) {
- break;
- }
- }
- if (count($shares2) === $limit) {
- break;
- }
- // If there was no limit on the select we are done
- if ($limit === -1) {
- break;
- }
- $offset += $added;
- // Fetch again $limit shares
- $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
- // No more shares means we are done
- if (empty($shares)) {
- break;
- }
- }
- $shares = $shares2;
- }
- return $shares;
- }
- /**
- * @inheritdoc
- */
- public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
- $provider = $this->factory->getProviderForType($shareType);
- return $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
- }
- /**
- * @inheritdoc
- */
- public function getShareById($id, $recipient = null) {
- if ($id === null) {
- throw new ShareNotFound();
- }
- list($providerId, $id) = $this->splitFullId($id);
- $provider = $this->factory->getProvider($providerId);
- $share = $provider->getShareById($id, $recipient);
- // Validate link shares expiration date
- if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
- $share->getExpirationDate() !== null &&
- $share->getExpirationDate() <= new \DateTime()) {
- $this->deleteShare($share);
- throw new ShareNotFound();
- }
- return $share;
- }
- /**
- * Get all the shares for a given path
- *
- * @param \OCP\Files\Node $path
- * @param int $page
- * @param int $perPage
- *
- * @return Share[]
- */
- public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
- }
- /**
- * Get the share by token possible with password
- *
- * @param string $token
- * @return Share
- *
- * @throws ShareNotFound
- */
- public function getShareByToken($token) {
- $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
- try {
- $share = $provider->getShareByToken($token);
- } catch (ShareNotFound $e) {
- //Ignore
- }
- // If it is not a link share try to fetch a federated share by token
- if ($share === null) {
- $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
- $share = $provider->getShareByToken($token);
- }
- if ($share->getExpirationDate() !== null &&
- $share->getExpirationDate() <= new \DateTime()) {
- $this->deleteShare($share);
- throw new ShareNotFound();
- }
- return $share;
- }
- /**
- * Verify the password of a public share
- *
- * @param \OCP\Share\IShare $share
- * @param string $password
- * @return bool
- */
- public function checkPassword(\OCP\Share\IShare $share, $password) {
- if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK) {
- //TODO maybe exception?
- return false;
- }
- if ($password === null || $share->getPassword() === null) {
- return false;
- }
- $newHash = '';
- if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
- return false;
- }
- if (!empty($newHash)) {
- $share->setPassword($newHash);
- $provider = $this->factory->getProviderForType($share->getShareType());
- $provider->update($share);
- }
- return true;
- }
- /**
- * Get access list to a path. This means
- * all the users and groups that can access a given path.
- *
- * Consider:
- * -root
- * |-folder1
- * |-folder2
- * |-fileA
- *
- * fileA is shared with user1
- * folder2 is shared with group2
- * folder1 is shared with user2
- *
- * Then the access list will to '/folder1/folder2/fileA' is:
- * [
- * 'users' => ['user1', 'user2'],
- * 'groups' => ['group2']
- * ]
- *
- * This is required for encryption
- *
- * @param \OCP\Files\Node $path
- */
- public function getAccessList(\OCP\Files\Node $path) {
- }
- /**
- * Create a new share
- * @return \OCP\Share\IShare;
- */
- public function newShare() {
- return new \OC\Share20\Share($this->rootFolder);
- }
- /**
- * Is the share API enabled
- *
- * @return bool
- */
- public function shareApiEnabled() {
- return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
- }
- /**
- * Is public link sharing enabled
- *
- * @return bool
- */
- public function shareApiAllowLinks() {
- return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
- }
- /**
- * Is password on public link requires
- *
- * @return bool
- */
- public function shareApiLinkEnforcePassword() {
- return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
- }
- /**
- * Is default expire date enabled
- *
- * @return bool
- */
- public function shareApiLinkDefaultExpireDate() {
- return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
- }
- /**
- * Is default expire date enforced
- *`
- * @return bool
- */
- public function shareApiLinkDefaultExpireDateEnforced() {
- return $this->shareApiLinkDefaultExpireDate() &&
- $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
- }
- /**
- * Number of default expire days
- *shareApiLinkAllowPublicUpload
- * @return int
- */
- public function shareApiLinkDefaultExpireDays() {
- return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
- }
- /**
- * Allow public upload on link shares
- *
- * @return bool
- */
- public function shareApiLinkAllowPublicUpload() {
- return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
- }
- /**
- * check if user can only share with group members
- * @return bool
- */
- public function shareWithGroupMembersOnly() {
- return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
- }
- /**
- * Check if users can share with groups
- * @return bool
- */
- public function allowGroupSharing() {
- return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
- }
- /**
- * Copied from \OC_Util::isSharingDisabledForUser
- *
- * TODO: Deprecate fuction from OC_Util
- *
- * @param string $userId
- * @return bool
- */
- public function sharingDisabledForUser($userId) {
- if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
- $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
- $excludedGroups = json_decode($groupsList);
- if (is_null($excludedGroups)) {
- $excludedGroups = explode(',', $groupsList);
- $newValue = json_encode($excludedGroups);
- $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
- }
- $user = $this->userManager->get($userId);
- $usersGroups = $this->groupManager->getUserGroupIds($user);
- if (!empty($usersGroups)) {
- $remainingGroups = array_diff($usersGroups, $excludedGroups);
- // if the user is only in groups which are disabled for sharing then
- // sharing is also disabled for the user
- if (empty($remainingGroups)) {
- return true;
- }
- }
- }
- return false;
- }
- /**
- * @inheritdoc
- */
- public function outgoingServer2ServerSharesAllowed() {
- return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
- }
- }
|