* @author Bjoern Schiessle * @author Björn Schießle * @author Daniel Calviño Sánchez * @author Jan-Christoph Borchardt * @author Joas Schilling * @author Julius Härtl * @author Lukas Reschke * @author Maxence Lange * @author Maxence Lange * @author Morris Jobke * @author Pauli Järvinen * @author Robin Appelman * @author Roeland Jago Douma * @author Stephan Müller * @author Vincent Petry * * @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 * */ namespace OC\Share20; use OC\Cache\CappedMemoryCache; use OC\Files\Mount\MoveableMount; use OC\HintException; use OC\Share20\Exception\ProviderException; use OCP\Files\File; use OCP\Files\Folder; use OCP\Files\IRootFolder; use OCP\Files\Mount\IMountManager; use OCP\Files\Node; use OCP\IConfig; use OCP\IGroupManager; use OCP\IL10N; use OCP\ILogger; use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserManager; use OCP\L10N\IFactory; use OCP\Mail\IMailer; use OCP\Security\IHasher; use OCP\Security\ISecureRandom; use OCP\Share\Exceptions\GenericShareException; use OCP\Share\Exceptions\ShareNotFound; use OCP\Share\IManager; use OCP\Share\IProviderFactory; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\GenericEvent; use OCP\Share\IShareProvider; use OCP\Share; /** * 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 IFactory */ private $l10nFactory; /** @var IUserManager */ private $userManager; /** @var IRootFolder */ private $rootFolder; /** @var CappedMemoryCache */ private $sharingDisabledForUsersCache; /** @var EventDispatcher */ private $eventDispatcher; /** @var LegacyHooks */ private $legacyHooks; /** @var IMailer */ private $mailer; /** @var IURLGenerator */ private $urlGenerator; /** @var \OC_Defaults */ private $defaults; /** * Manager constructor. * * @param ILogger $logger * @param IConfig $config * @param ISecureRandom $secureRandom * @param IHasher $hasher * @param IMountManager $mountManager * @param IGroupManager $groupManager * @param IL10N $l * @param IFactory $l10nFactory * @param IProviderFactory $factory * @param IUserManager $userManager * @param IRootFolder $rootFolder * @param EventDispatcher $eventDispatcher * @param IMailer $mailer * @param IURLGenerator $urlGenerator * @param \OC_Defaults $defaults */ public function __construct( ILogger $logger, IConfig $config, ISecureRandom $secureRandom, IHasher $hasher, IMountManager $mountManager, IGroupManager $groupManager, IL10N $l, IFactory $l10nFactory, IProviderFactory $factory, IUserManager $userManager, IRootFolder $rootFolder, EventDispatcher $eventDispatcher, IMailer $mailer, IURLGenerator $urlGenerator, \OC_Defaults $defaults ) { $this->logger = $logger; $this->config = $config; $this->secureRandom = $secureRandom; $this->hasher = $hasher; $this->mountManager = $mountManager; $this->groupManager = $groupManager; $this->l = $l; $this->l10nFactory = $l10nFactory; $this->factory = $factory; $this->userManager = $userManager; $this->rootFolder = $rootFolder; $this->eventDispatcher = $eventDispatcher; $this->sharingDisabledForUsersCache = new CappedMemoryCache(); $this->legacyHooks = new LegacyHooks($this->eventDispatcher); $this->mailer = $mailer; $this->urlGenerator = $urlGenerator; $this->defaults = $defaults; } /** * 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 * * @suppress PhanUndeclaredClassMethod */ 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 if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) { if ($share->getSharedWith() === null) { throw new \InvalidArgumentException('SharedWith should not be empty'); } } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) { $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith()); if ($circle === null) { throw new \InvalidArgumentException('SharedWith is not a valid circ
<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>jQuery UI Datepicker - Select a Date Range</title>
	<link rel="stylesheet" href="../../themes/base/all.css">
	<link rel="stylesheet" href="../demos.css">
	<script src="../../external/requirejs/require.js"></script>
	<script src="../bootstrap.js">
		var dateFormat = "mm/dd/yy",
			from = $( "#from" )
				.datepicker({
					defaultDate: "+1w",
					changeMonth: true,
					numberOfMonths: 3
				})
				.on( "change", function() {
					to.datepicker( "option", "minDate", getDate( this ) );
				}),
			to = $( "#to" ).datepicker({
				defaultDate: "+1w",
				changeMonth: true,
				numberOfMonths: 3
			})
			.on( "change", function() {
				from.datepicker( "option", "maxDate", getDate( this ) );
			});

		function getDate( element ) {
			var date;
			try {
				date = $.datepicker.parseDate( dateFormat, element.value );
			} catch( error ) {
				date = null;
			}

			return date;
		}
	</script>
</head>
<body>

<label for="from">From</label>
<input type="text" id="from" name="from">
<label for="to">to</label>
<input type="text" id="to" name="to">

<div class="demo-description">
<p>Select the date range to search for.</p>
</div>
</body>
</html>
'Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']); } else { $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']); } } else { $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']); } } else { $this->logger->debug('Share notification not send because mailsend is false.', ['app' => 'share']); } } return $share; } /** * @param IL10N $l Language of the recipient * @param string $filename file/folder name * @param string $link link to the file/folder * @param string $initiator user ID of share sender * @param string $shareWith email address of share receiver * @param \DateTime|null $expiration * @throws \Exception If mail couldn't be sent */ protected function sendMailNotification(IL10N $l, $filename, $link, $initiator, $shareWith, \DateTime $expiration = null) { $initiatorUser = $this->userManager->get($initiator); $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator; $message = $this->mailer->createMessage(); $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [ 'filename' => $filename, 'link' => $link, 'initiator' => $initiatorDisplayName, 'expiration' => $expiration, 'shareWith' => $shareWith, ]); $emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename))); $emailTemplate->addHeader(); $emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false); $text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]); $emailTemplate->addBodyText( $text . ' ' . $l->t('Click the button below to open it.'), $text ); $emailTemplate->addBodyButton( $l->t('Open »%s«', [$filename]), $link ); $message->setTo([$shareWith]); // The "From" contains the sharers name $instanceName = $this->defaults->getName(); $senderName = $l->t( '%s via %s', [ $initiatorDisplayName, $instanceName ] ); $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]); // The "Reply-To" is set to the sharer if an mail address is configured // also the default footer contains a "Do not reply" which needs to be adjusted. $initiatorEmail = $initiatorUser->getEMailAddress(); if($initiatorEmail !== null) { $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]); $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')); } else { $emailTemplate->addFooter(); } $message->useTemplate($emailTemplate); $this->mailer->send($message); } /** * 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); $this->updateSharePasswordIfNeeded($share, $originalShare); if ($share->getExpirationDate() != $originalShare->getExpirationDate()) { //Verify the expiration date $this->validateExpirationDate($share); $expirationDateUpdated = true; } } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) { $plainTextPassword = $share->getPassword(); if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) { $plainTextPassword = null; } } $this->pathCreateChecks($share->getNode()); // Now update the share! $provider = $this->factory->getProviderForType($share->getShareType()); if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) { $share = $provider->update($share, $plainTextPassword); } else { $share = $provider->update($share); } if ($expirationDateUpdated === true) { \OC_Hook::emit(Share::class, '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(Share::class, '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()) { if ($this->userManager->userExists($share->getShareOwner())) { $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner()); } else { $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy()); } \OC_Hook::emit(Share::class, '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; } /** * Updates the password of the given share if it is not the same as the * password of the original share. * * @param \OCP\Share\IShare $share the share to update its password. * @param \OCP\Share\IShare $originalShare the original share to compare its * password with. * @return boolean whether the password was updated or not. */ private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) { // 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())); return true; } } return false; } /** * 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'); } $event = new GenericEvent($share); $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event); // 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; // Emit post hook $event->setArgument('deletedShares', $deletedShares); $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event); } /** * 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->getFullId()); $provider = $this->factory->getProvider($providerId); $provider->deleteFromSelf($share, $recipientId); $event = new GenericEvent($share); $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event); } /** * @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()); if (is_null($sharedWith)) { throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist'); } $recipient = $this->userManager->get($recipientId); if (!$sharedWith->inGroup($recipient)) { throw new \InvalidArgumentException('Invalid recipient'); } } list($providerId, ) = $this->splitFullId($share->getFullId()); $provider = $this->factory->getProvider($providerId); $provider->move($share, $recipientId); } public function getSharesInFolder($userId, Folder $node, $reshares = false) { $providers = $this->factory->getAllProviders(); return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) { $newShares = $provider->getSharesInFolder($userId, $node, $reshares); foreach ($newShares as $fid => $data) { if (!isset($shares[$fid])) { $shares[$fid] = []; } $shares[$fid] = array_merge($shares[$fid], $data); } return $shares; }, []); } /** * @inheritdoc */ 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'); } try { $provider = $this->factory->getProviderForType($shareType); } catch (ProviderException $e) { return []; } $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset); /* * Work around so we don't return expired shares but still follow * proper pagination. */ $shares2 = []; while(true) { $added = 0; foreach ($shares as $share) { try { $this->checkExpireDate($share); } catch (ShareNotFound $e) { //Ignore since this basically means the share is deleted continue; } $added++; $shares2[] = $share; if (count($shares2) === $limit) { break; } } // If we did not fetch more shares than the limit then there are no more shares if (count($shares) < $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) { try { $provider = $this->factory->getProviderForType($shareType); } catch (ProviderException $e) { return []; } $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset); // remove all shares which are already expired foreach ($shares as $key => $share) { try { $this->checkExpireDate($share); } catch (ShareNotFound $e) { unset($shares[$key]); } } return $shares; } /** * @inheritdoc */ public function getShareById($id, $recipient = null) { if ($id === null) { throw new ShareNotFound(); } list($providerId, $id) = $this->splitFullId($id); try { $provider = $this->factory->getProvider($providerId); } catch (ProviderException $e) { throw new ShareNotFound(); } $share = $provider->getShareById($id, $recipient); $this->checkExpireDate($share); 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) { return []; } /** * Get the share by token possible with password * * @param string $token * @return Share * * @throws ShareNotFound */ public function getShareByToken($token) { $share = null; try { if($this->shareApiAllowLinks()) { $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK); $share = $provider->getShareByToken($token); } } catch (ProviderException $e) { } catch (ShareNotFound $e) { } // If it is not a link share try to fetch a federated share by token if ($share === null) { try { $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE); $share = $provider->getShareByToken($token); } catch (ProviderException $e) { } catch (ShareNotFound $e) { } } // If it is not a link share try to fetch a mail share by token if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) { try { $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL); $share = $provider->getShareByToken($token); } catch (ProviderException $e) { } catch (ShareNotFound $e) { } } if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) { try { $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE); $share = $provider->getShareByToken($token); } catch (ProviderException $e) { } catch (ShareNotFound $e) { } } if ($share === null) { throw new ShareNotFound($this->l->t('The requested share does not exist anymore')); } $this->checkExpireDate($share); /* * Reduce the permissions for link shares if public upload is not enabled */ if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK && !$this->shareApiLinkAllowPublicUpload()) { $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE)); } return $share; } protected function checkExpireDate($share) { if ($share->getExpirationDate() !== null && $share->getExpirationDate() <= new \DateTime()) { $this->deleteShare($share); throw new ShareNotFound($this->l->t('The requested share does not exist anymore')); } } /** * 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) { $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL; if (!$passwordProtected) { //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; } /** * @inheritdoc */ public function userDeleted($uid) { $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL]; foreach ($types as $type) { try { $provider = $this->factory->getProviderForType($type); } catch (ProviderException $e) { continue; } $provider->userDeleted($uid, $type); } } /** * @inheritdoc */ public function groupDeleted($gid) { $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP); $provider->groupDeleted($gid); } /** * @inheritdoc */ public function userDeletedFromGroup($uid, $gid) { $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP); $provider->userDeletedFromGroup($uid, $gid); } /** * Get access list to a path. This means * all the users that can access a given path. * * Consider: * -root * |-folder1 (23) * |-folder2 (32) * |-fileA (42) * * fileA is shared with user1 and user1@server1 * folder2 is shared with group2 (user4 is a member of group2) * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2 * * Then the access list to '/folder1/folder2/fileA' with $currentAccess is: * [ * users => [ * 'user1' => ['node_id' => 42, 'node_path' => '/fileA'], * 'user4' => ['node_id' => 32, 'node_path' => '/folder2'], * 'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'], * ], * remote => [ * 'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'], * 'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'], * ], * public => bool * mail => bool * ] * * The access list to '/folder1/folder2/fileA' **without** $currentAccess is: * [ * users => ['user1', 'user2', 'user4'], * remote => bool, * public => bool * mail => bool * ] * * This is required for encryption/activity * * @param \OCP\Files\Node $path * @param bool $recursive Should we check all parent folders as well * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it) * @return array */ public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) { $owner = $path->getOwner()->getUID(); if ($currentAccess) { $al = ['users' => [], 'remote' => [], 'public' => false]; } else { $al = ['users' => [], 'remote' => false, 'public' => false]; } if (!$this->userManager->userExists($owner)) { return $al; } //Get node for the owner $userFolder = $this->rootFolder->getUserFolder($owner); if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) { $path = $userFolder->getById($path->getId())[0]; } $providers = $this->factory->getAllProviders(); /** @var Node[] $nodes */ $nodes = []; if ($currentAccess) { $ownerPath = $path->getPath(); $ownerPath = explode('/', $ownerPath, 4); if (count($ownerPath) < 4) { $ownerPath = ''; } else { $ownerPath = $ownerPath[3]; } $al['users'][$owner] = [ 'node_id' => $path->getId(), 'node_path' => '/' . $ownerPath, ]; } else { $al['users'][] = $owner; } // Collect all the shares while ($path->getPath() !== $userFolder->getPath()) { $nodes[] = $path; if (!$recursive) { break; } $path = $path->getParent(); } foreach ($providers as $provider) { $tmp = $provider->getAccessList($nodes, $currentAccess); foreach ($tmp as $k => $v) { if (isset($al[$k])) { if (is_array($al[$k])) { if ($currentAccess) { $al[$k] += $v; } else { $al[$k] = array_merge($al[$k], $v); $al[$k] = array_unique($al[$k]); $al[$k] = array_values($al[$k]); } } else { $al[$k] = $al[$k] || $v; } } else { $al[$k] = $v; } } } return $al; } /** * Create a new share * @return \OCP\Share\IShare */ public function newShare() { return new \OC\Share20\Share($this->rootFolder, $this->userManager); } /** * 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 ($userId === null) { return false; } if (isset($this->sharingDisabledForUsersCache[$userId])) { return $this->sharingDisabledForUsersCache[$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)) { $this->sharingDisabledForUsersCache[$userId] = true; return true; } } } $this->sharingDisabledForUsersCache[$userId] = false; return false; } /** * @inheritdoc */ public function outgoingServer2ServerSharesAllowed() { return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes'; } /** * @inheritdoc */ public function shareProviderExists($shareType) { try { $this->factory->getProviderForType($shareType); } catch (ProviderException $e) { return false; } return true; } }