diff options
Diffstat (limited to 'apps/files_sharing/lib/Controller/ShareController.php')
-rw-r--r-- | apps/files_sharing/lib/Controller/ShareController.php | 383 |
1 files changed, 82 insertions, 301 deletions
diff --git a/apps/files_sharing/lib/Controller/ShareController.php b/apps/files_sharing/lib/Controller/ShareController.php index ae21259e21e..5a776379fce 100644 --- a/apps/files_sharing/lib/Controller/ShareController.php +++ b/apps/files_sharing/lib/Controller/ShareController.php @@ -1,156 +1,90 @@ <?php + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Daniel Calviño Sánchez <danxuliu@gmail.com> - * @author Georg Ehrke <oc.list@georgehrke.com> - * @author j3l11234 <297259024@qq.com> - * @author Joas Schilling <coding@schilljs.com> - * @author John Molakvoæ <skjnldsv@protonmail.com> - * @author Jonas Sulzer <jonas@violoncello.ch> - * @author Julius Härtl <jus@bitgrid.net> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author MartB <mart.b@outlook.de> - * @author Maxence Lange <maxence@pontapreta.net> - * @author Michael Weimann <mail@michael-weimann.eu> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Piotr Filiciak <piotr@filiciak.pl> - * @author Robin Appelman <robin@icewind.nl> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Sascha Sambale <mastixmc@gmail.com> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Vincent Petry <vincent@nextcloud.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/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Files_Sharing\Controller; use OC\Security\CSP\ContentSecurityPolicy; -use OC_Files; -use OC_Util; +use OCA\DAV\Connector\Sabre\PublicAuth; use OCA\FederatedFileSharing\FederatedShareProvider; -use OCA\Files_Sharing\Activity\Providers\Downloads; use OCA\Files_Sharing\Event\BeforeTemplateRenderedEvent; use OCA\Files_Sharing\Event\ShareLinkAccessedEvent; -use OCA\Viewer\Event\LoadViewer; use OCP\Accounts\IAccountManager; use OCP\AppFramework\AuthPublicShareController; +use OCP\AppFramework\Http\Attribute\NoCSRFRequired; +use OCP\AppFramework\Http\Attribute\OpenAPI; +use OCP\AppFramework\Http\Attribute\PublicPage; +use OCP\AppFramework\Http\DataResponse; use OCP\AppFramework\Http\NotFoundResponse; -use OCP\AppFramework\Http\Template\ExternalShareMenuAction; -use OCP\AppFramework\Http\Template\LinkMenuAction; -use OCP\AppFramework\Http\Template\PublicTemplateResponse; -use OCP\AppFramework\Http\Template\SimpleMenuAction; +use OCP\AppFramework\Http\RedirectResponse; +use OCP\AppFramework\Http\Response; use OCP\AppFramework\Http\TemplateResponse; +use OCP\Constants; use OCP\Defaults; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Files\File; use OCP\Files\Folder; use OCP\Files\IRootFolder; use OCP\Files\NotFoundException; +use OCP\HintException; use OCP\IConfig; use OCP\IL10N; -use OCP\ILogger; use OCP\IPreview; use OCP\IRequest; use OCP\ISession; use OCP\IURLGenerator; -use OCP\IUser; use OCP\IUserManager; +use OCP\Security\Events\GenerateSecurePasswordEvent; use OCP\Security\ISecureRandom; +use OCP\Security\PasswordContext; use OCP\Share; use OCP\Share\Exceptions\ShareNotFound; use OCP\Share\IManager as ShareManager; -use OCP\Share\IShare; use OCP\Share\IPublicShareTemplateFactory; -use OCP\Template; +use OCP\Share\IShare; /** - * Class ShareController - * * @package OCA\Files_Sharing\Controllers */ +#[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)] class ShareController extends AuthPublicShareController { - protected IConfig $config; - protected IUserManager $userManager; - protected ILogger $logger; - protected \OCP\Activity\IManager $activityManager; - protected IPreview $previewManager; - protected IRootFolder $rootFolder; - protected FederatedShareProvider $federatedShareProvider; - protected IAccountManager $accountManager; - protected IEventDispatcher $eventDispatcher; - protected IL10N $l10n; - protected Defaults $defaults; - protected ShareManager $shareManager; - protected ISecureRandom $secureRandom; - protected ?Share\IShare $share = null; - private IPublicShareTemplateFactory $publicShareTemplateFactory; + protected ?IShare $share = null; + + public const SHARE_ACCESS = 'access'; + public const SHARE_AUTH = 'auth'; + public const SHARE_DOWNLOAD = 'download'; public function __construct( string $appName, IRequest $request, - IConfig $config, + protected IConfig $config, IURLGenerator $urlGenerator, - IUserManager $userManager, - ILogger $logger, - \OCP\Activity\IManager $activityManager, - ShareManager $shareManager, + protected IUserManager $userManager, + protected \OCP\Activity\IManager $activityManager, + protected ShareManager $shareManager, ISession $session, - IPreview $previewManager, - IRootFolder $rootFolder, - FederatedShareProvider $federatedShareProvider, - IAccountManager $accountManager, - IEventDispatcher $eventDispatcher, - IL10N $l10n, - ISecureRandom $secureRandom, - Defaults $defaults, - IPublicShareTemplateFactory $publicShareTemplateFactory + protected IPreview $previewManager, + protected IRootFolder $rootFolder, + protected FederatedShareProvider $federatedShareProvider, + protected IAccountManager $accountManager, + protected IEventDispatcher $eventDispatcher, + protected IL10N $l10n, + protected ISecureRandom $secureRandom, + protected Defaults $defaults, + private IPublicShareTemplateFactory $publicShareTemplateFactory, ) { parent::__construct($appName, $request, $session, $urlGenerator); - - $this->config = $config; - $this->userManager = $userManager; - $this->logger = $logger; - $this->activityManager = $activityManager; - $this->previewManager = $previewManager; - $this->rootFolder = $rootFolder; - $this->federatedShareProvider = $federatedShareProvider; - $this->accountManager = $accountManager; - $this->eventDispatcher = $eventDispatcher; - $this->l10n = $l10n; - $this->secureRandom = $secureRandom; - $this->defaults = $defaults; - $this->shareManager = $shareManager; - $this->publicShareTemplateFactory = $publicShareTemplateFactory; } - public const SHARE_ACCESS = 'access'; - public const SHARE_AUTH = 'auth'; - public const SHARE_DOWNLOAD = 'download'; - /** - * @PublicPage - * @NoCSRFRequired - * * Show the authentication page * The form has to submit to the authenticate method route */ + #[PublicPage] + #[NoCSRFRequired] public function showAuthenticate(): TemplateResponse { $templateParameters = ['share' => $this->share]; @@ -212,7 +146,6 @@ class ShareController extends AuthPublicShareController { * @return bool */ protected function validateIdentity(?string $identityToken = null): bool { - if ($this->share->getShareType() !== IShare::TYPE_EMAIL) { return false; } @@ -228,7 +161,7 @@ class ShareController extends AuthPublicShareController { * Generates a password for the share, respecting any password policy defined */ protected function generatePassword(): void { - $event = new \OCP\Security\Events\GenerateSecurePasswordEvent(); + $event = new GenerateSecurePasswordEvent(PasswordContext::SHARING); $this->eventDispatcher->dispatchTyped($event); $password = $event->getPassword() ?? $this->secureRandom->generate(20); @@ -240,7 +173,7 @@ class ShareController extends AuthPublicShareController { return $this->shareManager->checkPassword($this->share, $password); } - protected function getPasswordHash(): string { + protected function getPasswordHash(): ?string { return $this->share->getPassword(); } @@ -259,8 +192,12 @@ class ShareController extends AuthPublicShareController { } protected function authSucceeded() { + if ($this->share === null) { + throw new NotFoundException(); + } + // For share this was always set so it is still used in other apps - $this->session->set('public_link_authenticated', (string)$this->share->getId()); + $this->session->set(PublicAuth::DAV_AUTHENTICATED, $this->share->getId()); } protected function authFailed() { @@ -271,12 +208,12 @@ class ShareController extends AuthPublicShareController { /** * throws hooks when a share is attempted to be accessed * - * @param \OCP\Share\IShare|string $share the Share instance if available, - * otherwise token + * @param IShare|string $share the Share instance if available, + * otherwise token * @param int $errorCode * @param string $errorMessage * - * @throws \OCP\HintException + * @throws HintException * @throws \OC\ServerNotAvailableException * * @deprecated use OCP\Files_Sharing\Event\ShareLinkAccessedEvent @@ -285,7 +222,7 @@ class ShareController extends AuthPublicShareController { $itemType = $itemSource = $uidOwner = ''; $token = $share; $exception = null; - if ($share instanceof \OCP\Share\IShare) { + if ($share instanceof IShare) { try { $token = $share->getToken(); $uidOwner = $share->getSharedBy(); @@ -315,9 +252,9 @@ class ShareController extends AuthPublicShareController { * Emit a ShareLinkAccessedEvent event when a share is accessed, downloaded, auth... */ protected function emitShareAccessEvent(IShare $share, string $step = '', int $errorCode = 200, string $errorMessage = ''): void { - if ($step !== self::SHARE_ACCESS && - $step !== self::SHARE_AUTH && - $step !== self::SHARE_DOWNLOAD) { + if ($step !== self::SHARE_ACCESS + && $step !== self::SHARE_AUTH + && $step !== self::SHARE_DOWNLOAD) { return; } $this->eventDispatcher->dispatchTyped(new ShareLinkAccessedEvent($share, $step, $errorCode, $errorMessage)); @@ -329,7 +266,7 @@ class ShareController extends AuthPublicShareController { * @param Share\IShare $share * @return bool */ - private function validateShare(\OCP\Share\IShare $share) { + private function validateShare(IShare $share) { // If the owner is disabled no access to the link is granted $owner = $this->userManager->get($share->getShareOwner()); if ($owner === null || !$owner->isEnabled()) { @@ -346,15 +283,13 @@ class ShareController extends AuthPublicShareController { } /** - * @PublicPage - * @NoCSRFRequired - * - * * @param string $path * @return TemplateResponse * @throws NotFoundException * @throws \Exception */ + #[PublicPage] + #[NoCSRFRequired] public function showShare($path = ''): TemplateResponse { \OC_User::setIncognitoMode(true); @@ -364,11 +299,11 @@ class ShareController extends AuthPublicShareController { } catch (ShareNotFound $e) { // The share does not exists, we do not emit an ShareLinkAccessedEvent $this->emitAccessShareHook($this->getToken(), 404, 'Share not found'); - throw new NotFoundException(); + throw new NotFoundException($this->l10n->t('This share does not exist or is no longer available')); } if (!$this->validateShare($share)) { - throw new NotFoundException(); + throw new NotFoundException($this->l10n->t('This share does not exist or is no longer available')); } $shareNode = $share->getNode(); @@ -379,15 +314,15 @@ class ShareController extends AuthPublicShareController { } catch (NotFoundException $e) { $this->emitAccessShareHook($share, 404, 'Share not found'); $this->emitShareAccessEvent($share, ShareController::SHARE_ACCESS, 404, 'Share not found'); - throw new NotFoundException(); + throw new NotFoundException($this->l10n->t('This share does not exist or is no longer available')); } // We can't get the path of a file share try { - if ($shareNode instanceof \OCP\Files\File && $path !== '') { + if ($shareNode instanceof File && $path !== '') { $this->emitAccessShareHook($share, 404, 'Share not found'); $this->emitShareAccessEvent($share, self::SHARE_ACCESS, 404, 'Share not found'); - throw new NotFoundException(); + throw new NotFoundException($this->l10n->t('This share does not exist or is no longer available')); } } catch (\Exception $e) { $this->emitAccessShareHook($share, 404, 'Share not found'); @@ -403,56 +338,38 @@ class ShareController extends AuthPublicShareController { } /** - * @PublicPage - * @NoCSRFRequired * @NoSameSiteCookieRequired * * @param string $token - * @param string $files + * @param string|null $files * @param string $path - * @param string $downloadStartSecret - * @return void|\OCP\AppFramework\Http\Response + * @return void|Response * @throws NotFoundException + * @deprecated 31.0.0 Users are encouraged to use the DAV endpoint */ - public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') { + #[PublicPage] + #[NoCSRFRequired] + public function downloadShare($token, $files = null, $path = '') { \OC_User::setIncognitoMode(true); $share = $this->shareManager->getShareByToken($token); - if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) { - return new \OCP\AppFramework\Http\DataResponse('Share has no read permission'); + if (!($share->getPermissions() & Constants::PERMISSION_READ)) { + return new DataResponse('Share has no read permission'); } - $files_list = null; - if (!is_null($files)) { // download selected files - $files_list = json_decode($files); - // in case we get only a single file - if ($files_list === null) { - $files_list = [$files]; - } - // Just in case $files is a single int like '1234' - if (!is_array($files_list)) { - $files_list = [$files_list]; - } + $attributes = $share->getAttributes(); + if ($attributes?->getAttribute('permissions', 'download') === false) { + return new DataResponse('Share has no download permission'); } if (!$this->validateShare($share)) { throw new NotFoundException(); } - $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner()); - $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath()); - - - // Single file share - if ($share->getNode() instanceof \OCP\Files\File) { - // Single file download - $this->singleFileDownloaded($share, $share->getNode()); - } - // Directory share - else { - /** @var \OCP\Files\Folder $node */ - $node = $share->getNode(); + $node = $share->getNode(); + if ($node instanceof Folder) { + // Directory share // Try to get the path if ($path !== '') { @@ -465,158 +382,22 @@ class ShareController extends AuthPublicShareController { } } - $originalSharePath = $userFolder->getRelativePath($node->getPath()); - - if ($node instanceof \OCP\Files\File) { - // Single file download - $this->singleFileDownloaded($share, $share->getNode()); - } else { - try { - if (!empty($files_list)) { - $this->fileListDownloaded($share, $files_list, $node); - } else { - // The folder is downloaded - $this->singleFileDownloaded($share, $share->getNode()); + if ($node instanceof Folder) { + if ($files === null || $files === '') { + if ($share->getHideDownload()) { + throw new NotFoundException('Downloading a folder'); } - } catch (NotFoundException $e) { - return new NotFoundResponse(); } } } - /* FIXME: We should do this all nicely in OCP */ - OC_Util::tearDownFS(); - OC_Util::setupFS($share->getShareOwner()); - - /** - * this sets a cookie to be able to recognize the start of the download - * the content must not be longer than 32 characters and must only contain - * alphanumeric characters - */ - if (!empty($downloadStartSecret) - && !isset($downloadStartSecret[32]) - && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) { - - // FIXME: set on the response once we use an actual app framework response - setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/'); - } - $this->emitAccessShareHook($share); $this->emitShareAccessEvent($share, self::SHARE_DOWNLOAD); - $server_params = [ 'head' => $this->request->getMethod() === 'HEAD' ]; - - /** - * Http range requests support - */ - if (isset($_SERVER['HTTP_RANGE'])) { - $server_params['range'] = $this->request->getHeader('Range'); - } - - // download selected files - if (!is_null($files) && $files !== '') { - // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well - // after dispatching the request which results in a "Cannot modify header information" notice. - OC_Files::get($originalSharePath, $files_list, $server_params); - exit(); - } else { - // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well - // after dispatching the request which results in a "Cannot modify header information" notice. - OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params); - exit(); - } - } - - /** - * create activity for every downloaded file - * - * @param Share\IShare $share - * @param array $files_list - * @param \OCP\Files\Folder $node - * @throws NotFoundException when trying to download a folder or multiple files of a "hide download" share - */ - protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) { - if ($share->getHideDownload() && count($files_list) > 1) { - throw new NotFoundException('Downloading more than 1 file'); - } - - foreach ($files_list as $file) { - $subNode = $node->get($file); - $this->singleFileDownloaded($share, $subNode); - } - } - - /** - * create activity if a single file was downloaded from a link share - * - * @param Share\IShare $share - * @throws NotFoundException when trying to download a folder of a "hide download" share - */ - protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) { - if ($share->getHideDownload() && $node instanceof Folder) { - throw new NotFoundException('Downloading a folder'); - } - - $fileId = $node->getId(); - - $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy()); - $userNodeList = $userFolder->getById($fileId); - $userNode = $userNodeList[0]; - $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner()); - $userPath = $userFolder->getRelativePath($userNode->getPath()); - $ownerPath = $ownerFolder->getRelativePath($node->getPath()); - $remoteAddress = $this->request->getRemoteAddress(); - $dateTime = new \DateTime(); - $dateTime = $dateTime->format('Y-m-d H'); - $remoteAddressHash = md5($dateTime . '-' . $remoteAddress); - - $parameters = [$userPath]; - - if ($share->getShareType() === IShare::TYPE_EMAIL) { - if ($node instanceof \OCP\Files\File) { - $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED; - } else { - $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED; - } - $parameters[] = $share->getSharedWith(); - } else { - if ($node instanceof \OCP\Files\File) { - $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED; - $parameters[] = $remoteAddressHash; - } else { - $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED; - $parameters[] = $remoteAddressHash; - } + $davUrl = '/public.php/dav/files/' . $token . '/?accept=zip'; + if ($files !== null) { + $davUrl .= '&files=' . $files; } - - $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath); - - if ($share->getShareOwner() !== $share->getSharedBy()) { - $parameters[0] = $ownerPath; - $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath); - } - } - - /** - * publish activity - * - * @param string $subject - * @param array $parameters - * @param string $affectedUser - * @param int $fileId - * @param string $filePath - */ - protected function publishActivity($subject, - array $parameters, - $affectedUser, - $fileId, - $filePath) { - $event = $this->activityManager->generateEvent(); - $event->setApp('files_sharing') - ->setType('public_links') - ->setSubject($subject, $parameters) - ->setAffectedUser($affectedUser) - ->setObject('files', $fileId, $filePath); - $this->activityManager->publish($event); + return new RedirectResponse($this->urlGenerator->getAbsoluteURL($davUrl)); } } |