]> source.dussan.org Git - nextcloud-server.git/commitdiff
Move files_sharing Controllers => Controller
authorRoeland Jago Douma <roeland@famdouma.nl>
Mon, 24 Oct 2016 09:46:25 +0000 (11:46 +0200)
committerRoeland Jago Douma <roeland@famdouma.nl>
Mon, 24 Oct 2016 09:46:25 +0000 (11:46 +0200)
lib/Controller is the default location for controllers. So lets put them
all in there.

Signed-off-by: Roeland Jago Douma <roeland@famdouma.nl>
apps/files_sharing/lib/AppInfo/Application.php
apps/files_sharing/lib/Controller/ExternalSharesController.php [new file with mode: 0644]
apps/files_sharing/lib/Controller/ShareController.php [new file with mode: 0644]
apps/files_sharing/lib/Controllers/ExternalSharesController.php [deleted file]
apps/files_sharing/lib/Controllers/ShareController.php [deleted file]
apps/files_sharing/lib/Middleware/SharingCheckMiddleware.php
apps/files_sharing/tests/Controller/ExternalShareControllerTest.php [new file with mode: 0644]
apps/files_sharing/tests/Controller/ShareControllerTest.php [new file with mode: 0644]
apps/files_sharing/tests/Controllers/ExternalShareControllerTest.php [deleted file]
apps/files_sharing/tests/Controllers/ShareControllerTest.php [deleted file]

index 29cdf702a514eb3aae12f4186b7b83beed1cad4b..922db7dac757040ed6b5fa084f2fe6f8a0ace94a 100644 (file)
@@ -32,8 +32,8 @@ use OCA\Files_Sharing\Middleware\OCSShareAPIMiddleware;
 use OCA\Files_Sharing\MountProvider;
 use OCP\AppFramework\App;
 use OC\AppFramework\Utility\SimpleContainer;
-use OCA\Files_Sharing\Controllers\ExternalSharesController;
-use OCA\Files_Sharing\Controllers\ShareController;
+use OCA\Files_Sharing\Controller\ExternalSharesController;
+use OCA\Files_Sharing\Controller\ShareController;
 use OCA\Files_Sharing\Middleware\SharingCheckMiddleware;
 use \OCP\IContainer;
 use OCP\IServerContainer;
diff --git a/apps/files_sharing/lib/Controller/ExternalSharesController.php b/apps/files_sharing/lib/Controller/ExternalSharesController.php
new file mode 100644 (file)
index 0000000..fe4c09d
--- /dev/null
@@ -0,0 +1,150 @@
+<?php
+/**
+ * @copyright Copyright (c) 2016, ownCloud, Inc.
+ *
+ * @author Björn Schießle <bjoern@schiessle.org>
+ * @author Lukas Reschke <lukas@statuscode.ch>
+ * @author Morris Jobke <hey@morrisjobke.de>
+ * @author Robin Appelman <robin@icewind.nl>
+ * @author Roeland Jago Douma <roeland@famdouma.nl>
+ *
+ * @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 OCA\Files_Sharing\Controller;
+
+use OCP\AppFramework\Controller;
+use OCP\IRequest;
+use OCP\AppFramework\Http\JSONResponse;
+use OCP\Http\Client\IClientService;
+use OCP\AppFramework\Http\DataResponse;
+
+/**
+ * Class ExternalSharesController
+ *
+ * @package OCA\Files_Sharing\Controller
+ */
+class ExternalSharesController extends Controller {
+
+       /** @var \OCA\Files_Sharing\External\Manager */
+       private $externalManager;
+       /** @var IClientService */
+       private $clientService;
+
+       /**
+        * @param string $appName
+        * @param IRequest $request
+        * @param \OCA\Files_Sharing\External\Manager $externalManager
+        * @param IClientService $clientService
+        */
+       public function __construct($appName,
+                                                               IRequest $request,
+                                                               \OCA\Files_Sharing\External\Manager $externalManager,
+                                                               IClientService $clientService) {
+               parent::__construct($appName, $request);
+               $this->externalManager = $externalManager;
+               $this->clientService = $clientService;
+       }
+
+       /**
+        * @NoAdminRequired
+        * @NoOutgoingFederatedSharingRequired
+        *
+        * @return JSONResponse
+        */
+       public function index() {
+               return new JSONResponse($this->externalManager->getOpenShares());
+       }
+
+       /**
+        * @NoAdminRequired
+        * @NoOutgoingFederatedSharingRequired
+        *
+        * @param int $id
+        * @return JSONResponse
+        */
+       public function create($id) {
+               $this->externalManager->acceptShare($id);
+               return new JSONResponse();
+       }
+
+       /**
+        * @NoAdminRequired
+        * @NoOutgoingFederatedSharingRequired
+        *
+        * @param integer $id
+        * @return JSONResponse
+        */
+       public function destroy($id) {
+               $this->externalManager->declineShare($id);
+               return new JSONResponse();
+       }
+
+       /**
+        * Test whether the specified remote is accessible
+        *
+        * @param string $remote
+        * @param bool $checkVersion
+        * @return bool
+        */
+       protected function testUrl($remote, $checkVersion = false) {
+               try {
+                       $client = $this->clientService->newClient();
+                       $response = json_decode($client->get(
+                               $remote,
+                               [
+                                       'timeout' => 3,
+                                       'connect_timeout' => 3,
+                               ]
+                       )->getBody());
+
+                       if ($checkVersion) {
+                               return !empty($response->version) && version_compare($response->version, '7.0.0', '>=');
+                       } else {
+                               return is_object($response);
+                       }
+               } catch (\Exception $e) {
+                       return false;
+               }
+       }
+
+       /**
+        * @PublicPage
+        * @NoOutgoingFederatedSharingRequired
+        * @NoIncomingFederatedSharingRequired
+        *
+        * @param string $remote
+        * @return DataResponse
+        */
+       public function testRemote($remote) {
+               if (
+                       $this->testUrl('https://' . $remote . '/ocs-provider/') ||
+                       $this->testUrl('https://' . $remote . '/ocs-provider/index.php') ||
+                       $this->testUrl('https://' . $remote . '/status.php', true)
+               ) {
+                       return new DataResponse('https');
+               } elseif (
+                       $this->testUrl('http://' . $remote . '/ocs-provider/') ||
+                       $this->testUrl('http://' . $remote . '/ocs-provider/index.php') ||
+                       $this->testUrl('http://' . $remote . '/status.php', true)
+               ) {
+                       return new DataResponse('http');
+               } else {
+                       return new DataResponse(false);
+               }
+       }
+
+}
diff --git a/apps/files_sharing/lib/Controller/ShareController.php b/apps/files_sharing/lib/Controller/ShareController.php
new file mode 100644 (file)
index 0000000..6272511
--- /dev/null
@@ -0,0 +1,577 @@
+<?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 Georg Ehrke <georg@owncloud.com>
+ * @author Joas Schilling <coding@schilljs.com>
+ * @author Lukas Reschke <lukas@statuscode.ch>
+ * @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 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 OCA\Files_Sharing\Controller;
+
+use OC_Files;
+use OC_Util;
+use OCA\FederatedFileSharing\FederatedShareProvider;
+use OCP\Defaults;
+use OCP\IL10N;
+use OCP\Template;
+use OCP\Share;
+use OCP\AppFramework\Controller;
+use OCP\IRequest;
+use OCP\AppFramework\Http\TemplateResponse;
+use OCP\AppFramework\Http\RedirectResponse;
+use OCP\AppFramework\Http\NotFoundResponse;
+use OCP\IURLGenerator;
+use OCP\IConfig;
+use OCP\ILogger;
+use OCP\IUserManager;
+use OCP\ISession;
+use OCP\IPreview;
+use OCP\Util;
+use OCA\Files_Sharing\Activity;
+use \OCP\Files\NotFoundException;
+use OCP\Files\IRootFolder;
+use OCP\Share\Exceptions\ShareNotFound;
+use Symfony\Component\EventDispatcher\EventDispatcherInterface;
+
+/**
+ * Class ShareController
+ *
+ * @package OCA\Files_Sharing\Controllers
+ */
+class ShareController extends Controller {
+
+       /** @var IConfig */
+       protected $config;
+       /** @var IURLGenerator */
+       protected $urlGenerator;
+       /** @var IUserManager */
+       protected $userManager;
+       /** @var ILogger */
+       protected $logger;
+       /** @var \OCP\Activity\IManager */
+       protected $activityManager;
+       /** @var \OCP\Share\IManager */
+       protected $shareManager;
+       /** @var ISession */
+       protected $session;
+       /** @var IPreview */
+       protected $previewManager;
+       /** @var IRootFolder */
+       protected $rootFolder;
+       /** @var FederatedShareProvider */
+       protected $federatedShareProvider;
+       /** @var EventDispatcherInterface */
+       protected $eventDispatcher;
+       /** @var IL10N */
+       protected $l10n;
+       /** @var Defaults */
+       protected $defaults;
+
+       /**
+        * @param string $appName
+        * @param IRequest $request
+        * @param IConfig $config
+        * @param IURLGenerator $urlGenerator
+        * @param IUserManager $userManager
+        * @param ILogger $logger
+        * @param \OCP\Activity\IManager $activityManager
+        * @param \OCP\Share\IManager $shareManager
+        * @param ISession $session
+        * @param IPreview $previewManager
+        * @param IRootFolder $rootFolder
+        * @param FederatedShareProvider $federatedShareProvider
+        * @param EventDispatcherInterface $eventDispatcher
+        * @param IL10N $l10n
+        * @param \OC_Defaults $defaults
+        */
+       public function __construct($appName,
+                                                               IRequest $request,
+                                                               IConfig $config,
+                                                               IURLGenerator $urlGenerator,
+                                                               IUserManager $userManager,
+                                                               ILogger $logger,
+                                                               \OCP\Activity\IManager $activityManager,
+                                                               \OCP\Share\IManager $shareManager,
+                                                               ISession $session,
+                                                               IPreview $previewManager,
+                                                               IRootFolder $rootFolder,
+                                                               FederatedShareProvider $federatedShareProvider,
+                                                               EventDispatcherInterface $eventDispatcher,
+                                                               IL10N $l10n,
+                                                               \OC_Defaults $defaults) {
+               parent::__construct($appName, $request);
+
+               $this->config = $config;
+               $this->urlGenerator = $urlGenerator;
+               $this->userManager = $userManager;
+               $this->logger = $logger;
+               $this->activityManager = $activityManager;
+               $this->shareManager = $shareManager;
+               $this->session = $session;
+               $this->previewManager = $previewManager;
+               $this->rootFolder = $rootFolder;
+               $this->federatedShareProvider = $federatedShareProvider;
+               $this->eventDispatcher = $eventDispatcher;
+               $this->l10n = $l10n;
+               $this->defaults = $defaults;
+       }
+
+       /**
+        * @PublicPage
+        * @NoCSRFRequired
+        *
+        * @param string $token
+        * @return TemplateResponse|RedirectResponse
+        */
+       public function showAuthenticate($token) {
+               $share = $this->shareManager->getShareByToken($token);
+
+               if($this->linkShareAuth($share)) {
+                       return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
+               }
+
+               return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
+       }
+
+       /**
+        * @PublicPage
+        * @UseSession
+        *
+        * Authenticates against password-protected shares
+        * @param string $token
+        * @param string $password
+        * @return RedirectResponse|TemplateResponse|NotFoundResponse
+        */
+       public function authenticate($token, $password = '') {
+
+               // Check whether share exists
+               try {
+                       $share = $this->shareManager->getShareByToken($token);
+               } catch (ShareNotFound $e) {
+                       return new NotFoundResponse();
+               }
+
+               $authenticate = $this->linkShareAuth($share, $password);
+
+               if($authenticate === true) {
+                       return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
+               }
+
+               return new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
+       }
+
+       /**
+        * Authenticate a link item with the given password.
+        * Or use the session if no password is provided.
+        *
+        * This is a modified version of Helper::authenticate
+        * TODO: Try to merge back eventually with Helper::authenticate
+        *
+        * @param \OCP\Share\IShare $share
+        * @param string|null $password
+        * @return bool
+        */
+       private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
+               if ($password !== null) {
+                       if ($this->shareManager->checkPassword($share, $password)) {
+                               $this->session->set('public_link_authenticated', (string)$share->getId());
+                       } else {
+                               $this->emitAccessShareHook($share, 403, 'Wrong password');
+                               return false;
+                       }
+               } else {
+                       // not authenticated ?
+                       if ( ! $this->session->exists('public_link_authenticated')
+                               || $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
+                               return false;
+                       }
+               }
+               return true;
+       }
+
+       /**
+        * throws hooks when a share is attempted to be accessed
+        *
+        * @param \OCP\Share\IShare|string $share the Share instance if available,
+        * otherwise token
+        * @param int $errorCode
+        * @param string $errorMessage
+        * @throws \OC\HintException
+        * @throws \OC\ServerNotAvailableException
+        */
+       protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
+               $itemType = $itemSource = $uidOwner = '';
+               $token = $share;
+               $exception = null;
+               if($share instanceof \OCP\Share\IShare) {
+                       try {
+                               $token = $share->getToken();
+                               $uidOwner = $share->getSharedBy();
+                               $itemType = $share->getNodeType();
+                               $itemSource = $share->getNodeId();
+                       } catch (\Exception $e) {
+                               // we log what we know and pass on the exception afterwards
+                               $exception = $e;
+                       }
+               }
+               \OC_Hook::emit('OCP\Share', 'share_link_access', [
+                       'itemType' => $itemType,
+                       'itemSource' => $itemSource,
+                       'uidOwner' => $uidOwner,
+                       'token' => $token,
+                       'errorCode' => $errorCode,
+                       'errorMessage' => $errorMessage,
+               ]);
+               if(!is_null($exception)) {
+                       throw $exception;
+               }
+       }
+
+       /**
+        * Validate the permissions of the share
+        *
+        * @param Share\IShare $share
+        * @return bool
+        */
+       private function validateShare(\OCP\Share\IShare $share) {
+               return $share->getNode()->isReadable() && $share->getNode()->isShareable();
+       }
+
+       /**
+        * @PublicPage
+        * @NoCSRFRequired
+        *
+        * @param string $token
+        * @param string $path
+        * @return TemplateResponse|RedirectResponse|NotFoundResponse
+        * @throws NotFoundException
+        * @throws \Exception
+        */
+       public function showShare($token, $path = '') {
+               \OC_User::setIncognitoMode(true);
+
+               // Check whether share exists
+               try {
+                       $share = $this->shareManager->getShareByToken($token);
+               } catch (ShareNotFound $e) {
+                       $this->emitAccessShareHook($token, 404, 'Share not found');
+                       return new NotFoundResponse();
+               }
+
+               // Share is password protected - check whether the user is permitted to access the share
+               if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
+                       return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
+                               array('token' => $token)));
+               }
+
+               if (!$this->validateShare($share)) {
+                       throw new NotFoundException();
+               }
+               // We can't get the path of a file share
+               try {
+                       if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
+                               $this->emitAccessShareHook($share, 404, 'Share not found');
+                               throw new NotFoundException();
+                       }
+               } catch (\Exception $e) {
+                       $this->emitAccessShareHook($share, 404, 'Share not found');
+                       throw $e;
+               }
+
+               $shareTmpl = [];
+               $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
+               $shareTmpl['owner'] = $share->getShareOwner();
+               $shareTmpl['filename'] = $share->getNode()->getName();
+               $shareTmpl['directory_path'] = $share->getTarget();
+               $shareTmpl['mimetype'] = $share->getNode()->getMimetype();
+               $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
+               $shareTmpl['dirToken'] = $token;
+               $shareTmpl['sharingToken'] = $token;
+               $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
+               $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
+               $shareTmpl['dir'] = '';
+               $shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
+               $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
+
+               // Show file list
+               $hideFileList = false;
+               if ($share->getNode() instanceof \OCP\Files\Folder) {
+                       /** @var \OCP\Files\Folder $rootFolder */
+                       $rootFolder = $share->getNode();
+
+                       try {
+                               $folderNode = $rootFolder->get($path);
+                       } catch (\OCP\Files\NotFoundException $e) {
+                               $this->emitAccessShareHook($share, 404, 'Share not found');
+                               throw new NotFoundException();
+                       }
+
+                       $shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
+
+                       /*
+                        * The OC_Util methods require a view. This just uses the node API
+                        */
+                       $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
+                       if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
+                               $freeSpace = max($freeSpace, 0);
+                       } else {
+                               $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
+                       }
+
+                       $uploadLimit = Util::uploadLimit();
+                       $maxUploadFilesize = min($freeSpace, $uploadLimit);
+                       $hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
+
+                       $folder = new Template('files', 'list', '');
+                       $folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
+                       $folder->assign('dirToken', $token);
+                       $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
+                       $folder->assign('isPublic', true);
+                       $folder->assign('hideFileList', $hideFileList);
+                       $folder->assign('publicUploadEnabled', 'no');
+                       $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
+                       $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
+                       $folder->assign('freeSpace', $freeSpace);
+                       $folder->assign('uploadLimit', $uploadLimit); // PHP upload limit
+                       $folder->assign('usedSpacePercent', 0);
+                       $folder->assign('trash', false);
+                       $shareTmpl['folder'] = $folder->fetchPage();
+               }
+
+               $shareTmpl['hideFileList'] = $hideFileList;
+               $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
+               $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
+               $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
+               $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
+               $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
+               $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
+               $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
+               $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
+               if ($shareTmpl['previewSupported']) {
+                       $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'core_ajax_public_preview',
+                               ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
+               } else {
+                       $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
+               }
+
+               // Load files we need
+               \OCP\Util::addScript('files', 'file-upload');
+               \OCP\Util::addStyle('files_sharing', 'public');
+               \OCP\Util::addStyle('files_sharing', 'mobile');
+               \OCP\Util::addScript('files_sharing', 'public');
+               \OCP\Util::addScript('files', 'fileactions');
+               \OCP\Util::addScript('files', 'fileactionsmenu');
+               \OCP\Util::addScript('files', 'jquery.fileupload');
+               \OCP\Util::addScript('files_sharing', 'files_drop');
+
+               if (isset($shareTmpl['folder'])) {
+                       // JS required for folders
+                       \OCP\Util::addStyle('files', 'files');
+                       \OCP\Util::addStyle('files', 'upload');
+                       \OCP\Util::addScript('files', 'filesummary');
+                       \OCP\Util::addScript('files', 'breadcrumb');
+                       \OCP\Util::addScript('files', 'fileinfomodel');
+                       \OCP\Util::addScript('files', 'newfilemenu');
+                       \OCP\Util::addScript('files', 'files');
+                       \OCP\Util::addScript('files', 'filelist');
+                       \OCP\Util::addScript('files', 'keyboardshortcuts');
+               }
+
+               // OpenGraph Support: http://ogp.me/
+               \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
+               \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
+               \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
+               \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
+               \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
+               \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $shareTmpl['previewImage']]);
+
+               $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
+
+               $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
+               $csp->addAllowedFrameDomain('\'self\'');
+               $response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
+               $response->setContentSecurityPolicy($csp);
+
+               $this->emitAccessShareHook($share);
+
+               return $response;
+       }
+
+       /**
+        * @PublicPage
+        * @NoCSRFRequired
+        *
+        * @param string $token
+        * @param string $files
+        * @param string $path
+        * @param string $downloadStartSecret
+        * @return void|\OCP\AppFramework\Http\Response
+        * @throws NotFoundException
+        */
+       public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
+               \OC_User::setIncognitoMode(true);
+
+               $share = $this->shareManager->getShareByToken($token);
+
+               if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
+                       return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
+               }
+
+               // Share is password protected - check whether the user is permitted to access the share
+               if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
+                       return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
+                               ['token' => $token]));
+               }
+
+               $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];
+                       }
+               }
+
+               $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
+               $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
+
+               if (!$this->validateShare($share)) {
+                       throw new NotFoundException();
+               }
+
+               // Single file share
+               if ($share->getNode() instanceof \OCP\Files\File) {
+                       // Single file download
+                       $event = $this->activityManager->generateEvent();
+                       $event->setApp('files_sharing')
+                               ->setType(Activity::TYPE_PUBLIC_LINKS)
+                               ->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED, [$userFolder->getRelativePath($share->getNode()->getPath())])
+                               ->setAffectedUser($share->getShareOwner())
+                               ->setObject('files', $share->getNode()->getId(), $userFolder->getRelativePath($share->getNode()->getPath()));
+                       $this->activityManager->publish($event);
+               }
+               // Directory share
+               else {
+                       /** @var \OCP\Files\Folder $node */
+                       $node = $share->getNode();
+
+                       // Try to get the path
+                       if ($path !== '') {
+                               try {
+                                       $node = $node->get($path);
+                               } catch (NotFoundException $e) {
+                                       $this->emitAccessShareHook($share, 404, 'Share not found');
+                                       return new NotFoundResponse();
+                               }
+                       }
+
+                       $originalSharePath = $userFolder->getRelativePath($node->getPath());
+
+                       if ($node instanceof \OCP\Files\File) {
+                               // Single file download
+                               $event = $this->activityManager->generateEvent();
+                               $event->setApp('files_sharing')
+                                       ->setType(Activity::TYPE_PUBLIC_LINKS)
+                                       ->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED, [$userFolder->getRelativePath($node->getPath())])
+                                       ->setAffectedUser($share->getShareOwner())
+                                       ->setObject('files', $node->getId(), $userFolder->getRelativePath($node->getPath()));
+                               $this->activityManager->publish($event);
+                       } else if (!empty($files_list)) {
+                               /** @var \OCP\Files\Folder $node */
+
+                               // Subset of files is downloaded
+                               foreach ($files_list as $file) {
+                                       $subNode = $node->get($file);
+
+                                       $event = $this->activityManager->generateEvent();
+                                       $event->setApp('files_sharing')
+                                               ->setType(Activity::TYPE_PUBLIC_LINKS)
+                                               ->setAffectedUser($share->getShareOwner())
+                                               ->setObject('files', $subNode->getId(), $userFolder->getRelativePath($subNode->getPath()));
+
+                                       if ($subNode instanceof \OCP\Files\File) {
+                                               $event->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED, [$userFolder->getRelativePath($subNode->getPath())]);
+                                       } else {
+                                               $event->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED, [$userFolder->getRelativePath($subNode->getPath())]);
+                                       }
+
+                                       $this->activityManager->publish($event);
+                               }
+                       } else {
+                               // The folder is downloaded
+                               $event = $this->activityManager->generateEvent();
+                               $event->setApp('files_sharing')
+                                       ->setType(Activity::TYPE_PUBLIC_LINKS)
+                                       ->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED, [$userFolder->getRelativePath($node->getPath())])
+                                       ->setAffectedUser($share->getShareOwner())
+                                       ->setObject('files', $node->getId(), $userFolder->getRelativePath($node->getPath()));
+                               $this->activityManager->publish($event);
+                       }
+               }
+
+               /* 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);
+
+               $server_params = array( '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();
+               }
+       }
+}
diff --git a/apps/files_sharing/lib/Controllers/ExternalSharesController.php b/apps/files_sharing/lib/Controllers/ExternalSharesController.php
deleted file mode 100644 (file)
index 24b3211..0000000
+++ /dev/null
@@ -1,150 +0,0 @@
-<?php
-/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @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 OCA\Files_Sharing\Controllers;
-
-use OCP\AppFramework\Controller;
-use OCP\IRequest;
-use OCP\AppFramework\Http\JSONResponse;
-use OCP\Http\Client\IClientService;
-use OCP\AppFramework\Http\DataResponse;
-
-/**
- * Class ExternalSharesController
- *
- * @package OCA\Files_Sharing\Controllers
- */
-class ExternalSharesController extends Controller {
-
-       /** @var \OCA\Files_Sharing\External\Manager */
-       private $externalManager;
-       /** @var IClientService */
-       private $clientService;
-
-       /**
-        * @param string $appName
-        * @param IRequest $request
-        * @param \OCA\Files_Sharing\External\Manager $externalManager
-        * @param IClientService $clientService
-        */
-       public function __construct($appName,
-                                                               IRequest $request,
-                                                               \OCA\Files_Sharing\External\Manager $externalManager,
-                                                               IClientService $clientService) {
-               parent::__construct($appName, $request);
-               $this->externalManager = $externalManager;
-               $this->clientService = $clientService;
-       }
-
-       /**
-        * @NoAdminRequired
-        * @NoOutgoingFederatedSharingRequired
-        *
-        * @return JSONResponse
-        */
-       public function index() {
-               return new JSONResponse($this->externalManager->getOpenShares());
-       }
-
-       /**
-        * @NoAdminRequired
-        * @NoOutgoingFederatedSharingRequired
-        *
-        * @param int $id
-        * @return JSONResponse
-        */
-       public function create($id) {
-               $this->externalManager->acceptShare($id);
-               return new JSONResponse();
-       }
-
-       /**
-        * @NoAdminRequired
-        * @NoOutgoingFederatedSharingRequired
-        *
-        * @param integer $id
-        * @return JSONResponse
-        */
-       public function destroy($id) {
-               $this->externalManager->declineShare($id);
-               return new JSONResponse();
-       }
-
-       /**
-        * Test whether the specified remote is accessible
-        *
-        * @param string $remote
-        * @param bool $checkVersion
-        * @return bool
-        */
-       protected function testUrl($remote, $checkVersion = false) {
-               try {
-                       $client = $this->clientService->newClient();
-                       $response = json_decode($client->get(
-                               $remote,
-                               [
-                                       'timeout' => 3,
-                                       'connect_timeout' => 3,
-                               ]
-                       )->getBody());
-
-                       if ($checkVersion) {
-                               return !empty($response->version) && version_compare($response->version, '7.0.0', '>=');
-                       } else {
-                               return is_object($response);
-                       }
-               } catch (\Exception $e) {
-                       return false;
-               }
-       }
-
-       /**
-        * @PublicPage
-        * @NoOutgoingFederatedSharingRequired
-        * @NoIncomingFederatedSharingRequired
-        *
-        * @param string $remote
-        * @return DataResponse
-        */
-       public function testRemote($remote) {
-               if (
-                       $this->testUrl('https://' . $remote . '/ocs-provider/') ||
-                       $this->testUrl('https://' . $remote . '/ocs-provider/index.php') ||
-                       $this->testUrl('https://' . $remote . '/status.php', true)
-               ) {
-                       return new DataResponse('https');
-               } elseif (
-                       $this->testUrl('http://' . $remote . '/ocs-provider/') ||
-                       $this->testUrl('http://' . $remote . '/ocs-provider/index.php') ||
-                       $this->testUrl('http://' . $remote . '/status.php', true)
-               ) {
-                       return new DataResponse('http');
-               } else {
-                       return new DataResponse(false);
-               }
-       }
-
-}
diff --git a/apps/files_sharing/lib/Controllers/ShareController.php b/apps/files_sharing/lib/Controllers/ShareController.php
deleted file mode 100644 (file)
index 8e34053..0000000
+++ /dev/null
@@ -1,577 +0,0 @@
-<?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 Georg Ehrke <georg@owncloud.com>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @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 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 OCA\Files_Sharing\Controllers;
-
-use OC_Files;
-use OC_Util;
-use OCA\FederatedFileSharing\FederatedShareProvider;
-use OCP\Defaults;
-use OCP\IL10N;
-use OCP\Template;
-use OCP\Share;
-use OCP\AppFramework\Controller;
-use OCP\IRequest;
-use OCP\AppFramework\Http\TemplateResponse;
-use OCP\AppFramework\Http\RedirectResponse;
-use OCP\AppFramework\Http\NotFoundResponse;
-use OCP\IURLGenerator;
-use OCP\IConfig;
-use OCP\ILogger;
-use OCP\IUserManager;
-use OCP\ISession;
-use OCP\IPreview;
-use OCP\Util;
-use OCA\Files_Sharing\Activity;
-use \OCP\Files\NotFoundException;
-use OCP\Files\IRootFolder;
-use OCP\Share\Exceptions\ShareNotFound;
-use Symfony\Component\EventDispatcher\EventDispatcherInterface;
-
-/**
- * Class ShareController
- *
- * @package OCA\Files_Sharing\Controllers
- */
-class ShareController extends Controller {
-
-       /** @var IConfig */
-       protected $config;
-       /** @var IURLGenerator */
-       protected $urlGenerator;
-       /** @var IUserManager */
-       protected $userManager;
-       /** @var ILogger */
-       protected $logger;
-       /** @var \OCP\Activity\IManager */
-       protected $activityManager;
-       /** @var \OCP\Share\IManager */
-       protected $shareManager;
-       /** @var ISession */
-       protected $session;
-       /** @var IPreview */
-       protected $previewManager;
-       /** @var IRootFolder */
-       protected $rootFolder;
-       /** @var FederatedShareProvider */
-       protected $federatedShareProvider;
-       /** @var EventDispatcherInterface */
-       protected $eventDispatcher;
-       /** @var IL10N */
-       protected $l10n;
-       /** @var Defaults */
-       protected $defaults;
-
-       /**
-        * @param string $appName
-        * @param IRequest $request
-        * @param IConfig $config
-        * @param IURLGenerator $urlGenerator
-        * @param IUserManager $userManager
-        * @param ILogger $logger
-        * @param \OCP\Activity\IManager $activityManager
-        * @param \OCP\Share\IManager $shareManager
-        * @param ISession $session
-        * @param IPreview $previewManager
-        * @param IRootFolder $rootFolder
-        * @param FederatedShareProvider $federatedShareProvider
-        * @param EventDispatcherInterface $eventDispatcher
-        * @param IL10N $l10n
-        * @param \OC_Defaults $defaults
-        */
-       public function __construct($appName,
-                                                               IRequest $request,
-                                                               IConfig $config,
-                                                               IURLGenerator $urlGenerator,
-                                                               IUserManager $userManager,
-                                                               ILogger $logger,
-                                                               \OCP\Activity\IManager $activityManager,
-                                                               \OCP\Share\IManager $shareManager,
-                                                               ISession $session,
-                                                               IPreview $previewManager,
-                                                               IRootFolder $rootFolder,
-                                                               FederatedShareProvider $federatedShareProvider,
-                                                               EventDispatcherInterface $eventDispatcher,
-                                                               IL10N $l10n,
-                                                               \OC_Defaults $defaults) {
-               parent::__construct($appName, $request);
-
-               $this->config = $config;
-               $this->urlGenerator = $urlGenerator;
-               $this->userManager = $userManager;
-               $this->logger = $logger;
-               $this->activityManager = $activityManager;
-               $this->shareManager = $shareManager;
-               $this->session = $session;
-               $this->previewManager = $previewManager;
-               $this->rootFolder = $rootFolder;
-               $this->federatedShareProvider = $federatedShareProvider;
-               $this->eventDispatcher = $eventDispatcher;
-               $this->l10n = $l10n;
-               $this->defaults = $defaults;
-       }
-
-       /**
-        * @PublicPage
-        * @NoCSRFRequired
-        *
-        * @param string $token
-        * @return TemplateResponse|RedirectResponse
-        */
-       public function showAuthenticate($token) {
-               $share = $this->shareManager->getShareByToken($token);
-
-               if($this->linkShareAuth($share)) {
-                       return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
-               }
-
-               return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
-       }
-
-       /**
-        * @PublicPage
-        * @UseSession
-        *
-        * Authenticates against password-protected shares
-        * @param string $token
-        * @param string $password
-        * @return RedirectResponse|TemplateResponse|NotFoundResponse
-        */
-       public function authenticate($token, $password = '') {
-
-               // Check whether share exists
-               try {
-                       $share = $this->shareManager->getShareByToken($token);
-               } catch (ShareNotFound $e) {
-                       return new NotFoundResponse();
-               }
-
-               $authenticate = $this->linkShareAuth($share, $password);
-
-               if($authenticate === true) {
-                       return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
-               }
-
-               return new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
-       }
-
-       /**
-        * Authenticate a link item with the given password.
-        * Or use the session if no password is provided.
-        *
-        * This is a modified version of Helper::authenticate
-        * TODO: Try to merge back eventually with Helper::authenticate
-        *
-        * @param \OCP\Share\IShare $share
-        * @param string|null $password
-        * @return bool
-        */
-       private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
-               if ($password !== null) {
-                       if ($this->shareManager->checkPassword($share, $password)) {
-                               $this->session->set('public_link_authenticated', (string)$share->getId());
-                       } else {
-                               $this->emitAccessShareHook($share, 403, 'Wrong password');
-                               return false;
-                       }
-               } else {
-                       // not authenticated ?
-                       if ( ! $this->session->exists('public_link_authenticated')
-                               || $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
-                               return false;
-                       }
-               }
-               return true;
-       }
-
-       /**
-        * throws hooks when a share is attempted to be accessed
-        *
-        * @param \OCP\Share\IShare|string $share the Share instance if available,
-        * otherwise token
-        * @param int $errorCode
-        * @param string $errorMessage
-        * @throws \OC\HintException
-        * @throws \OC\ServerNotAvailableException
-        */
-       protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
-               $itemType = $itemSource = $uidOwner = '';
-               $token = $share;
-               $exception = null;
-               if($share instanceof \OCP\Share\IShare) {
-                       try {
-                               $token = $share->getToken();
-                               $uidOwner = $share->getSharedBy();
-                               $itemType = $share->getNodeType();
-                               $itemSource = $share->getNodeId();
-                       } catch (\Exception $e) {
-                               // we log what we know and pass on the exception afterwards
-                               $exception = $e;
-                       }
-               }
-               \OC_Hook::emit('OCP\Share', 'share_link_access', [
-                       'itemType' => $itemType,
-                       'itemSource' => $itemSource,
-                       'uidOwner' => $uidOwner,
-                       'token' => $token,
-                       'errorCode' => $errorCode,
-                       'errorMessage' => $errorMessage,
-               ]);
-               if(!is_null($exception)) {
-                       throw $exception;
-               }
-       }
-
-       /**
-        * Validate the permissions of the share
-        *
-        * @param Share\IShare $share
-        * @return bool
-        */
-       private function validateShare(\OCP\Share\IShare $share) {
-               return $share->getNode()->isReadable() && $share->getNode()->isShareable();
-       }
-
-       /**
-        * @PublicPage
-        * @NoCSRFRequired
-        *
-        * @param string $token
-        * @param string $path
-        * @return TemplateResponse|RedirectResponse|NotFoundResponse
-        * @throws NotFoundException
-        * @throws \Exception
-        */
-       public function showShare($token, $path = '') {
-               \OC_User::setIncognitoMode(true);
-
-               // Check whether share exists
-               try {
-                       $share = $this->shareManager->getShareByToken($token);
-               } catch (ShareNotFound $e) {
-                       $this->emitAccessShareHook($token, 404, 'Share not found');
-                       return new NotFoundResponse();
-               }
-
-               // Share is password protected - check whether the user is permitted to access the share
-               if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
-                       return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
-                               array('token' => $token)));
-               }
-
-               if (!$this->validateShare($share)) {
-                       throw new NotFoundException();
-               }
-               // We can't get the path of a file share
-               try {
-                       if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
-                               $this->emitAccessShareHook($share, 404, 'Share not found');
-                               throw new NotFoundException();
-                       }
-               } catch (\Exception $e) {
-                       $this->emitAccessShareHook($share, 404, 'Share not found');
-                       throw $e;
-               }
-
-               $shareTmpl = [];
-               $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
-               $shareTmpl['owner'] = $share->getShareOwner();
-               $shareTmpl['filename'] = $share->getNode()->getName();
-               $shareTmpl['directory_path'] = $share->getTarget();
-               $shareTmpl['mimetype'] = $share->getNode()->getMimetype();
-               $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
-               $shareTmpl['dirToken'] = $token;
-               $shareTmpl['sharingToken'] = $token;
-               $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
-               $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
-               $shareTmpl['dir'] = '';
-               $shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
-               $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
-
-               // Show file list
-               $hideFileList = false;
-               if ($share->getNode() instanceof \OCP\Files\Folder) {
-                       /** @var \OCP\Files\Folder $rootFolder */
-                       $rootFolder = $share->getNode();
-
-                       try {
-                               $folderNode = $rootFolder->get($path);
-                       } catch (\OCP\Files\NotFoundException $e) {
-                               $this->emitAccessShareHook($share, 404, 'Share not found');
-                               throw new NotFoundException();
-                       }
-
-                       $shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
-
-                       /*
-                        * The OC_Util methods require a view. This just uses the node API
-                        */
-                       $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
-                       if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
-                               $freeSpace = max($freeSpace, 0);
-                       } else {
-                               $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
-                       }
-
-                       $uploadLimit = Util::uploadLimit();
-                       $maxUploadFilesize = min($freeSpace, $uploadLimit);
-                       $hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
-
-                       $folder = new Template('files', 'list', '');
-                       $folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
-                       $folder->assign('dirToken', $token);
-                       $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
-                       $folder->assign('isPublic', true);
-                       $folder->assign('hideFileList', $hideFileList);
-                       $folder->assign('publicUploadEnabled', 'no');
-                       $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
-                       $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
-                       $folder->assign('freeSpace', $freeSpace);
-                       $folder->assign('uploadLimit', $uploadLimit); // PHP upload limit
-                       $folder->assign('usedSpacePercent', 0);
-                       $folder->assign('trash', false);
-                       $shareTmpl['folder'] = $folder->fetchPage();
-               }
-
-               $shareTmpl['hideFileList'] = $hideFileList;
-               $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
-               $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
-               $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
-               $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
-               $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
-               $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
-               $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
-               $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
-               if ($shareTmpl['previewSupported']) {
-                       $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'core_ajax_public_preview',
-                               ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
-               } else {
-                       $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
-               }
-
-               // Load files we need
-               \OCP\Util::addScript('files', 'file-upload');
-               \OCP\Util::addStyle('files_sharing', 'public');
-               \OCP\Util::addStyle('files_sharing', 'mobile');
-               \OCP\Util::addScript('files_sharing', 'public');
-               \OCP\Util::addScript('files', 'fileactions');
-               \OCP\Util::addScript('files', 'fileactionsmenu');
-               \OCP\Util::addScript('files', 'jquery.fileupload');
-               \OCP\Util::addScript('files_sharing', 'files_drop');
-
-               if (isset($shareTmpl['folder'])) {
-                       // JS required for folders
-                       \OCP\Util::addStyle('files', 'files');
-                       \OCP\Util::addStyle('files', 'upload');
-                       \OCP\Util::addScript('files', 'filesummary');
-                       \OCP\Util::addScript('files', 'breadcrumb');
-                       \OCP\Util::addScript('files', 'fileinfomodel');
-                       \OCP\Util::addScript('files', 'newfilemenu');
-                       \OCP\Util::addScript('files', 'files');
-                       \OCP\Util::addScript('files', 'filelist');
-                       \OCP\Util::addScript('files', 'keyboardshortcuts');
-               }
-
-               // OpenGraph Support: http://ogp.me/
-               \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
-               \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
-               \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
-               \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
-               \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
-               \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $shareTmpl['previewImage']]);
-
-               $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
-
-               $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
-               $csp->addAllowedFrameDomain('\'self\'');
-               $response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
-               $response->setContentSecurityPolicy($csp);
-
-               $this->emitAccessShareHook($share);
-
-               return $response;
-       }
-
-       /**
-        * @PublicPage
-        * @NoCSRFRequired
-        *
-        * @param string $token
-        * @param string $files
-        * @param string $path
-        * @param string $downloadStartSecret
-        * @return void|\OCP\AppFramework\Http\Response
-        * @throws NotFoundException
-        */
-       public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
-               \OC_User::setIncognitoMode(true);
-
-               $share = $this->shareManager->getShareByToken($token);
-
-               if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
-                       return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
-               }
-
-               // Share is password protected - check whether the user is permitted to access the share
-               if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
-                       return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
-                               ['token' => $token]));
-               }
-
-               $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];
-                       }
-               }
-
-               $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
-               $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
-
-               if (!$this->validateShare($share)) {
-                       throw new NotFoundException();
-               }
-
-               // Single file share
-               if ($share->getNode() instanceof \OCP\Files\File) {
-                       // Single file download
-                       $event = $this->activityManager->generateEvent();
-                       $event->setApp('files_sharing')
-                               ->setType(Activity::TYPE_PUBLIC_LINKS)
-                               ->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED, [$userFolder->getRelativePath($share->getNode()->getPath())])
-                               ->setAffectedUser($share->getShareOwner())
-                               ->setObject('files', $share->getNode()->getId(), $userFolder->getRelativePath($share->getNode()->getPath()));
-                       $this->activityManager->publish($event);
-               }
-               // Directory share
-               else {
-                       /** @var \OCP\Files\Folder $node */
-                       $node = $share->getNode();
-
-                       // Try to get the path
-                       if ($path !== '') {
-                               try {
-                                       $node = $node->get($path);
-                               } catch (NotFoundException $e) {
-                                       $this->emitAccessShareHook($share, 404, 'Share not found');
-                                       return new NotFoundResponse();
-                               }
-                       }
-
-                       $originalSharePath = $userFolder->getRelativePath($node->getPath());
-
-                       if ($node instanceof \OCP\Files\File) {
-                               // Single file download
-                               $event = $this->activityManager->generateEvent();
-                               $event->setApp('files_sharing')
-                                       ->setType(Activity::TYPE_PUBLIC_LINKS)
-                                       ->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED, [$userFolder->getRelativePath($node->getPath())])
-                                       ->setAffectedUser($share->getShareOwner())
-                                       ->setObject('files', $node->getId(), $userFolder->getRelativePath($node->getPath()));
-                               $this->activityManager->publish($event);
-                       } else if (!empty($files_list)) {
-                               /** @var \OCP\Files\Folder $node */
-
-                               // Subset of files is downloaded
-                               foreach ($files_list as $file) {
-                                       $subNode = $node->get($file);
-
-                                       $event = $this->activityManager->generateEvent();
-                                       $event->setApp('files_sharing')
-                                               ->setType(Activity::TYPE_PUBLIC_LINKS)
-                                               ->setAffectedUser($share->getShareOwner())
-                                               ->setObject('files', $subNode->getId(), $userFolder->getRelativePath($subNode->getPath()));
-
-                                       if ($subNode instanceof \OCP\Files\File) {
-                                               $event->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED, [$userFolder->getRelativePath($subNode->getPath())]);
-                                       } else {
-                                               $event->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED, [$userFolder->getRelativePath($subNode->getPath())]);
-                                       }
-
-                                       $this->activityManager->publish($event);
-                               }
-                       } else {
-                               // The folder is downloaded
-                               $event = $this->activityManager->generateEvent();
-                               $event->setApp('files_sharing')
-                                       ->setType(Activity::TYPE_PUBLIC_LINKS)
-                                       ->setSubject(Activity::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED, [$userFolder->getRelativePath($node->getPath())])
-                                       ->setAffectedUser($share->getShareOwner())
-                                       ->setObject('files', $node->getId(), $userFolder->getRelativePath($node->getPath()));
-                               $this->activityManager->publish($event);
-                       }
-               }
-
-               /* 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);
-
-               $server_params = array( '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();
-               }
-       }
-}
index 7c5eb5afbdc12a5a5776d5e702688817f8153e8e..7e9109bf2d1cc2c656a631d33380ae9995b38729 100644 (file)
@@ -78,10 +78,10 @@ class SharingCheckMiddleware extends Middleware {
                        throw new NotFoundException('Sharing is disabled.');
                }
 
-               if ($controller instanceof \OCA\Files_Sharing\Controllers\ExternalSharesController &&
+               if ($controller instanceof \OCA\Files_Sharing\Controller\ExternalSharesController &&
                        !$this->externalSharesChecks()) {
                        throw new S2SException('Federated sharing not allowed');
-               } else if ($controller instanceof \OCA\Files_Sharing\Controllers\ShareController &&
+               } else if ($controller instanceof \OCA\Files_Sharing\Controller\ShareController &&
                        !$this->isLinkSharingEnabled()) {
                        throw new NotFoundException('Link sharing is disabled');
                }
diff --git a/apps/files_sharing/tests/Controller/ExternalShareControllerTest.php b/apps/files_sharing/tests/Controller/ExternalShareControllerTest.php
new file mode 100644 (file)
index 0000000..71a4f4a
--- /dev/null
@@ -0,0 +1,156 @@
+<?php
+/**
+ * @copyright Copyright (c) 2016, ownCloud, Inc.
+ *
+ * @author Joas Schilling <coding@schilljs.com>
+ * @author Lukas Reschke <lukas@statuscode.ch>
+ * @author Roeland Jago Douma <roeland@famdouma.nl>
+ *
+ * @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 OCA\Files_Sharing\Tests\Controllers;
+
+use OCA\Files_Sharing\Controller\ExternalSharesController;
+use OCP\AppFramework\Http\DataResponse;
+use OCP\AppFramework\Http\JSONResponse;
+use OCP\Http\Client\IClientService;
+use OCP\IRequest;
+
+/**
+ * Class ExternalShareControllerTest
+ *
+ * @package OCA\Files_Sharing\Controllers
+ */
+class ExternalShareControllerTest extends \Test\TestCase {
+       /** @var IRequest */
+       private $request;
+       /** @var \OCA\Files_Sharing\External\Manager */
+       private $externalManager;
+       /** @var IClientService */
+       private $clientService;
+
+       public function setUp() {
+               parent::setUp();
+               $this->request = $this->getMockBuilder('\\OCP\\IRequest')
+                       ->disableOriginalConstructor()->getMock();
+               $this->externalManager = $this->getMockBuilder('\\OCA\\Files_Sharing\\External\\Manager')
+                       ->disableOriginalConstructor()->getMock();
+               $this->clientService = $this->getMockBuilder('\\OCP\Http\\Client\\IClientService')
+                       ->disableOriginalConstructor()->getMock();
+       }
+
+       /**
+        * @return ExternalSharesController
+        */
+       public function getExternalShareController() {
+               return new ExternalSharesController(
+                       'files_sharing',
+                       $this->request,
+                       $this->externalManager,
+                       $this->clientService
+               );
+       }
+
+       public function testIndex() {
+               $this->externalManager
+                       ->expects($this->once())
+                       ->method('getOpenShares')
+                       ->will($this->returnValue(['MyDummyArray']));
+
+               $this->assertEquals(new JSONResponse(['MyDummyArray']), $this->getExternalShareController()->index());
+       }
+
+       public function testCreate() {
+               $this->externalManager
+                       ->expects($this->once())
+                       ->method('acceptShare')
+                       ->with(4);
+
+               $this->assertEquals(new JSONResponse(), $this->getExternalShareController()->create(4));
+       }
+
+       public function testDestroy() {
+               $this->externalManager
+                       ->expects($this->once())
+                       ->method('declineShare')
+                       ->with(4);
+
+               $this->assertEquals(new JSONResponse(), $this->getExternalShareController()->destroy(4));
+       }
+
+       public function testRemoteWithValidHttps() {
+               $client = $this->getMockBuilder('\\OCP\\Http\\Client\\IClient')
+                       ->disableOriginalConstructor()->getMock();
+               $response = $this->getMockBuilder('\\OCP\\Http\\Client\\IResponse')
+                       ->disableOriginalConstructor()->getMock();
+               $response
+                       ->expects($this->exactly(2))
+                       ->method('getBody')
+                       ->will($this->onConsecutiveCalls('Certainly not a JSON string', '{"installed":true,"maintenance":false,"version":"8.1.0.8","versionstring":"8.1.0","edition":""}'));
+               $client
+                       ->expects($this->any())
+                       ->method('get')
+                       ->will($this->returnValue($response));
+
+               $this->clientService
+                       ->expects($this->exactly(2))
+                       ->method('newClient')
+                       ->will($this->returnValue($client));
+
+               $this->assertEquals(new DataResponse('https'), $this->getExternalShareController()->testRemote('owncloud.org'));
+       }
+
+       public function testRemoteWithWorkingHttp() {
+               $client = $this->getMockBuilder('\\OCP\\Http\\Client\\IClient')
+                       ->disableOriginalConstructor()->getMock();
+               $response = $this->getMockBuilder('\\OCP\\Http\\Client\\IResponse')
+                       ->disableOriginalConstructor()->getMock();
+               $client
+                       ->method('get')
+                       ->will($this->returnValue($response));
+               $response
+                       ->expects($this->exactly(5))
+                       ->method('getBody')
+                       ->will($this->onConsecutiveCalls('Certainly not a JSON string', 'Certainly not a JSON string', 'Certainly not a JSON string', 'Certainly not a JSON string', '{"installed":true,"maintenance":false,"version":"8.1.0.8","versionstring":"8.1.0","edition":""}'));
+               $this->clientService
+                       ->expects($this->exactly(5))
+                       ->method('newClient')
+                       ->will($this->returnValue($client));
+
+               $this->assertEquals(new DataResponse('http'), $this->getExternalShareController()->testRemote('owncloud.org'));
+       }
+
+       public function testRemoteWithInvalidRemote() {
+               $client = $this->getMockBuilder('\\OCP\\Http\\Client\\IClient')
+                       ->disableOriginalConstructor()->getMock();
+               $response = $this->getMockBuilder('\\OCP\\Http\\Client\\IResponse')
+                       ->disableOriginalConstructor()->getMock();
+               $client
+                       ->method('get')
+                       ->will($this->returnValue($response));
+               $response
+                       ->expects($this->exactly(6))
+                       ->method('getBody')
+                       ->will($this->returnValue('Certainly not a JSON string'));
+               $this->clientService
+                       ->expects($this->exactly(6))
+                       ->method('newClient')
+                       ->will($this->returnValue($client));
+
+               $this->assertEquals(new DataResponse(false), $this->getExternalShareController()->testRemote('owncloud.org'));
+       }
+}
diff --git a/apps/files_sharing/tests/Controller/ShareControllerTest.php b/apps/files_sharing/tests/Controller/ShareControllerTest.php
new file mode 100644 (file)
index 0000000..dae7740
--- /dev/null
@@ -0,0 +1,502 @@
+<?php
+/**
+ * @copyright Copyright (c) 2016, ownCloud, Inc.
+ *
+ * @author Bjoern Schiessle <bjoern@schiessle.org>
+ * @author Björn Schießle <bjoern@schiessle.org>
+ * @author Georg Ehrke <georg@owncloud.com>
+ * @author Joas Schilling <coding@schilljs.com>
+ * @author Lukas Reschke <lukas@statuscode.ch>
+ * @author Morris Jobke <hey@morrisjobke.de>
+ * @author Robin Appelman <robin@icewind.nl>
+ * @author Roeland Jago Douma <roeland@famdouma.nl>
+ * @author Thomas Müller <thomas.mueller@tmit.eu>
+ * @author Vincent Cloutier <vincent1cloutier@gmail.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 OCA\Files_Sharing\Tests\Controllers;
+
+use OC\Files\Filesystem;
+use OCA\FederatedFileSharing\FederatedShareProvider;
+use OCA\Files_Sharing\Controller\ShareController;
+use OCP\AppFramework\Http\DataResponse;
+use OCP\Share\Exceptions\ShareNotFound;
+use OCP\AppFramework\Http\NotFoundResponse;
+use OCP\AppFramework\Http\RedirectResponse;
+use OCP\AppFramework\Http\TemplateResponse;
+use OCP\ISession;
+use OCP\IUserManager;
+use OCP\Security\ISecureRandom;
+use OCP\IURLGenerator;
+use Symfony\Component\EventDispatcher\EventDispatcherInterface;
+
+/**
+ * @group DB
+ *
+ * @package OCA\Files_Sharing\Controllers
+ */
+class ShareControllerTest extends \Test\TestCase {
+
+       /** @var string */
+       private $user;
+       /** @var string */
+       private $oldUser;
+
+       /** @var string */
+       private $appName = 'files_sharing';
+       /** @var ShareController */
+       private $shareController;
+       /** @var IURLGenerator | \PHPUnit_Framework_MockObject_MockObject */
+       private $urlGenerator;
+       /** @var ISession | \PHPUnit_Framework_MockObject_MockObject */
+       private $session;
+       /** @var \OCP\IPreview | \PHPUnit_Framework_MockObject_MockObject */
+       private $previewManager;
+       /** @var \OCP\IConfig | \PHPUnit_Framework_MockObject_MockObject */
+       private $config;
+       /** @var  \OC\Share20\Manager | \PHPUnit_Framework_MockObject_MockObject */
+       private $shareManager;
+       /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject */
+       private $userManager;
+       /** @var  FederatedShareProvider | \PHPUnit_Framework_MockObject_MockObject */
+       private $federatedShareProvider;
+       /** @var EventDispatcherInterface | \PHPUnit_Framework_MockObject_MockObject */
+       private $eventDispatcher;
+
+       protected function setUp() {
+               parent::setUp();
+               $this->appName = 'files_sharing';
+
+               $this->shareManager = $this->getMockBuilder('\OC\Share20\Manager')->disableOriginalConstructor()->getMock();
+               $this->urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator')->getMock();
+               $this->session = $this->getMockBuilder('\OCP\ISession')->getMock();
+               $this->previewManager = $this->getMockBuilder('\OCP\IPreview')->getMock();
+               $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock();
+               $this->userManager = $this->getMockBuilder('\OCP\IUserManager')->getMock();
+               $this->federatedShareProvider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider')
+                       ->disableOriginalConstructor()->getMock();
+               $this->federatedShareProvider->expects($this->any())
+                       ->method('isOutgoingServer2serverShareEnabled')->willReturn(true);
+               $this->federatedShareProvider->expects($this->any())
+                       ->method('isIncomingServer2serverShareEnabled')->willReturn(true);
+               $this->eventDispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
+
+               $this->shareController = new \OCA\Files_Sharing\Controller\ShareController(
+                       $this->appName,
+                       $this->getMockBuilder('\OCP\IRequest')->getMock(),
+                       $this->config,
+                       $this->urlGenerator,
+                       $this->userManager,
+                       $this->getMockBuilder('\OCP\ILogger')->getMock(),
+                       $this->getMockBuilder('\OCP\Activity\IManager')->getMock(),
+                       $this->shareManager,
+                       $this->session,
+                       $this->previewManager,
+                       $this->getMockBuilder('\OCP\Files\IRootFolder')->getMock(),
+                       $this->federatedShareProvider,
+                       $this->eventDispatcher,
+                       $this->getMockBuilder('\OCP\IL10N')->getMock(),
+                       $this->getMockBuilder('\OC_Defaults')->getMock()
+               );
+
+
+               // Store current user
+               $this->oldUser = \OC_User::getUser();
+
+               // Create a dummy user
+               $this->user = \OC::$server->getSecureRandom()->generate(12, ISecureRandom::CHAR_LOWER);
+
+               \OC::$server->getUserManager()->createUser($this->user, $this->user);
+               \OC_Util::tearDownFS();
+               $this->loginAsUser($this->user);
+       }
+
+       protected function tearDown() {
+               \OC_Util::tearDownFS();
+               \OC_User::setUserId('');
+               Filesystem::tearDown();
+               $user = \OC::$server->getUserManager()->get($this->user);
+               if ($user !== null) { $user->delete(); }
+               \OC_User::setIncognitoMode(false);
+
+               \OC::$server->getSession()->set('public_link_authenticated', '');
+
+               // Set old user
+               \OC_User::setUserId($this->oldUser);
+               \OC_Util::setupFS($this->oldUser);
+               parent::tearDown();
+       }
+
+       public function testShowAuthenticateNotAuthenticated() {
+               $share = \OC::$server->getShareManager()->newShare();
+
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('getShareByToken')
+                       ->with('token')
+                       ->willReturn($share);
+
+               $response = $this->shareController->showAuthenticate('token');
+               $expectedResponse =  new TemplateResponse($this->appName, 'authenticate', [], 'guest');
+               $this->assertEquals($expectedResponse, $response);
+       }
+
+       public function testShowAuthenticateAuthenticatedForDifferentShare() {
+               $share = \OC::$server->getShareManager()->newShare();
+               $share->setId(1);
+
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('getShareByToken')
+                       ->with('token')
+                       ->willReturn($share);
+
+               $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
+               $this->session->method('get')->with('public_link_authenticated')->willReturn('2');
+
+               $response = $this->shareController->showAuthenticate('token');
+               $expectedResponse =  new TemplateResponse($this->appName, 'authenticate', [], 'guest');
+               $this->assertEquals($expectedResponse, $response);
+       }
+
+       public function testShowAuthenticateCorrectShare() {
+               $share = \OC::$server->getShareManager()->newShare();
+               $share->setId(1);
+
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('getShareByToken')
+                       ->with('token')
+                       ->willReturn($share);
+
+               $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
+               $this->session->method('get')->with('public_link_authenticated')->willReturn('1');
+
+               $this->urlGenerator->expects($this->once())
+                       ->method('linkToRoute')
+                       ->with('files_sharing.sharecontroller.showShare', ['token' => 'token'])
+                       ->willReturn('redirect');
+
+               $response = $this->shareController->showAuthenticate('token');
+               $expectedResponse =  new RedirectResponse('redirect');
+               $this->assertEquals($expectedResponse, $response);
+       }
+
+       public function testAuthenticateInvalidToken() {
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('getShareByToken')
+                       ->with('token')
+                       ->will($this->throwException(new \OCP\Share\Exceptions\ShareNotFound()));
+
+               $response = $this->shareController->authenticate('token');
+               $expectedResponse =  new NotFoundResponse();
+               $this->assertEquals($expectedResponse, $response);
+       }
+
+       public function testAuthenticateValidPassword() {
+               $share = \OC::$server->getShareManager()->newShare();
+               $share->setId(42);
+
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('getShareByToken')
+                       ->with('token')
+                       ->willReturn($share);
+
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('checkPassword')
+                       ->with($share, 'validpassword')
+                       ->willReturn(true);
+
+               $this->session
+                       ->expects($this->once())
+                       ->method('set')
+                       ->with('public_link_authenticated', '42');
+
+               $this->urlGenerator->expects($this->once())
+                       ->method('linkToRoute')
+                       ->with('files_sharing.sharecontroller.showShare', ['token'=>'token'])
+                       ->willReturn('redirect');
+
+               $response = $this->shareController->authenticate('token', 'validpassword');
+               $expectedResponse =  new RedirectResponse('redirect');
+               $this->assertEquals($expectedResponse, $response);
+       }
+
+       public function testAuthenticateInvalidPassword() {
+               $share = \OC::$server->getShareManager()->newShare();
+               $share->setNodeId(100)
+                       ->setNodeType('file')
+                       ->setToken('token')
+                       ->setSharedBy('initiator')
+                       ->setId(42);
+
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('getShareByToken')
+                       ->with('token')
+                       ->willReturn($share);
+
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('checkPassword')
+                       ->with($share, 'invalidpassword')
+                       ->willReturn(false);
+
+               $this->session
+                       ->expects($this->never())
+                       ->method('set');
+
+               $hookListner = $this->getMockBuilder('Dummy')->setMethods(['access'])->getMock();
+               \OCP\Util::connectHook('OCP\Share', 'share_link_access',  $hookListner, 'access');
+
+               $hookListner->expects($this->once())
+                       ->method('access')
+                       ->with($this->callback(function(array $data) {
+                               return $data['itemType'] === 'file' &&
+                                       $data['itemSource'] === 100 &&
+                                       $data['uidOwner'] === 'initiator' &&
+                                       $data['token'] === 'token' &&
+                                       $data['errorCode'] === 403 &&
+                                       $data['errorMessage'] === 'Wrong password';
+                       }));
+
+               $response = $this->shareController->authenticate('token', 'invalidpassword');
+               $expectedResponse =  new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
+               $this->assertEquals($expectedResponse, $response);
+       }
+
+       public function testShowShareInvalidToken() {
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('getShareByToken')
+                       ->with('invalidtoken')
+                       ->will($this->throwException(new ShareNotFound()));
+
+               // Test without a not existing token
+               $response = $this->shareController->showShare('invalidtoken');
+               $expectedResponse =  new NotFoundResponse();
+               $this->assertEquals($expectedResponse, $response);
+       }
+
+       public function testShowShareNotAuthenticated() {
+               $share = \OC::$server->getShareManager()->newShare();
+               $share->setPassword('password');
+
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('getShareByToken')
+                       ->with('validtoken')
+                       ->willReturn($share);
+
+               $this->urlGenerator->expects($this->once())
+                       ->method('linkToRoute')
+                       ->with('files_sharing.sharecontroller.authenticate', ['token' => 'validtoken'])
+                       ->willReturn('redirect');
+
+               // Test without a not existing token
+               $response = $this->shareController->showShare('validtoken');
+               $expectedResponse = new RedirectResponse('redirect');
+               $this->assertEquals($expectedResponse, $response);
+       }
+
+
+       public function testShowShare() {
+               $owner = $this->getMockBuilder('OCP\IUser')->getMock();
+               $owner->method('getDisplayName')->willReturn('ownerDisplay');
+               $owner->method('getUID')->willReturn('ownerUID');
+
+               $file = $this->getMockBuilder('OCP\Files\File')->getMock();
+               $file->method('getName')->willReturn('file1.txt');
+               $file->method('getMimetype')->willReturn('text/plain');
+               $file->method('getSize')->willReturn(33);
+               $file->method('isReadable')->willReturn(true);
+               $file->method('isShareable')->willReturn(true);
+
+               $share = \OC::$server->getShareManager()->newShare();
+               $share->setId(42);
+               $share->setPassword('password')
+                       ->setShareOwner('ownerUID')
+                       ->setNode($file)
+                       ->setTarget('/file1.txt');
+
+               $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
+               $this->session->method('get')->with('public_link_authenticated')->willReturn('42');
+
+               $this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
+
+               $this->config->method('getSystemValue')
+                       ->willReturnMap(
+                               [
+                                       ['max_filesize_animated_gifs_public_sharing', 10, 10],
+                                       ['enable_previews', true, true],
+                                       ['preview_max_x', 1024, 1024],
+                                       ['preview_max_y', 1024, 1024],
+                               ]
+                       );
+               $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
+               $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
+
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('getShareByToken')
+                       ->with('token')
+                       ->willReturn($share);
+               $this->config
+                       ->expects($this->once())
+                       ->method('getAppValue')
+                       ->with('core', 'shareapi_public_link_disclaimertext', null)
+                       ->willReturn('My disclaimer text');
+
+               $this->userManager->method('get')->with('ownerUID')->willReturn($owner);
+
+               $this->eventDispatcher->expects($this->once())
+                       ->method('dispatch')
+                       ->with('OCA\Files_Sharing::loadAdditionalScripts');
+
+               $response = $this->shareController->showShare('token');
+               $sharedTmplParams = array(
+                       'displayName' => 'ownerDisplay',
+                       'owner' => 'ownerUID',
+                       'filename' => 'file1.txt',
+                       'directory_path' => '/file1.txt',
+                       'mimetype' => 'text/plain',
+                       'dirToken' => 'token',
+                       'sharingToken' => 'token',
+                       'server2serversharing' => true,
+                       'protected' => 'true',
+                       'dir' => '',
+                       'downloadURL' => null,
+                       'fileSize' => '33 B',
+                       'nonHumanFileSize' => 33,
+                       'maxSizeAnimateGif' => 10,
+                       'previewSupported' => true,
+                       'previewEnabled' => true,
+                       'previewMaxX' => 1024,
+                       'previewMaxY' => 1024,
+                       'hideFileList' => false,
+                       'shareOwner' => 'ownerDisplay',
+                       'disclaimer' => 'My disclaimer text',
+                       'shareUrl' => null,
+                       'previewImage' => null
+               );
+
+               $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
+               $csp->addAllowedFrameDomain('\'self\'');
+               $expectedResponse = new TemplateResponse($this->appName, 'public', $sharedTmplParams, 'base');
+               $expectedResponse->setContentSecurityPolicy($csp);
+
+               $this->assertEquals($expectedResponse, $response);
+       }
+
+       /**
+        * @expectedException \OCP\Files\NotFoundException
+        */
+       public function testShowShareInvalid() {
+               $owner = $this->getMockBuilder('OCP\IUser')->getMock();
+               $owner->method('getDisplayName')->willReturn('ownerDisplay');
+               $owner->method('getUID')->willReturn('ownerUID');
+
+               $file = $this->getMockBuilder('OCP\Files\File')->getMock();
+               $file->method('getName')->willReturn('file1.txt');
+               $file->method('getMimetype')->willReturn('text/plain');
+               $file->method('getSize')->willReturn(33);
+               $file->method('isShareable')->willReturn(false);
+               $file->method('isReadable')->willReturn(true);
+
+               $share = \OC::$server->getShareManager()->newShare();
+               $share->setId(42);
+               $share->setPassword('password')
+                       ->setShareOwner('ownerUID')
+                       ->setNode($file)
+                       ->setTarget('/file1.txt');
+
+               $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
+               $this->session->method('get')->with('public_link_authenticated')->willReturn('42');
+
+               $this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
+
+               $this->config->method('getSystemValue')
+                       ->willReturnMap(
+                               [
+                                       ['max_filesize_animated_gifs_public_sharing', 10, 10],
+                                       ['enable_previews', true, true],
+                               ]
+                       );
+               $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
+               $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
+
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('getShareByToken')
+                       ->with('token')
+                       ->willReturn($share);
+
+               $this->userManager->method('get')->with('ownerUID')->willReturn($owner);
+
+               $this->shareController->showShare('token');
+       }
+
+       public function testDownloadShare() {
+               $share = $this->getMockBuilder('\OCP\Share\IShare')->getMock();
+               $share->method('getPassword')->willReturn('password');
+               $share
+                       ->expects($this->once())
+                       ->method('getPermissions')
+                       ->willReturn(\OCP\Constants::PERMISSION_READ);
+
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('getShareByToken')
+                       ->with('validtoken')
+                       ->willReturn($share);
+
+               $this->urlGenerator->expects($this->once())
+                       ->method('linkToRoute')
+                       ->with('files_sharing.sharecontroller.authenticate', ['token' => 'validtoken'])
+                       ->willReturn('redirect');
+
+               // Test with a password protected share and no authentication
+               $response = $this->shareController->downloadShare('validtoken');
+               $expectedResponse = new RedirectResponse('redirect');
+               $this->assertEquals($expectedResponse, $response);
+       }
+
+       public function testDownloadShareWithCreateOnlyShare() {
+               $share = $this->getMockBuilder('\OCP\Share\IShare')->getMock();
+               $share->method('getPassword')->willReturn('password');
+               $share
+                       ->expects($this->once())
+                       ->method('getPermissions')
+                       ->willReturn(\OCP\Constants::PERMISSION_CREATE);
+
+               $this->shareManager
+                       ->expects($this->once())
+                       ->method('getShareByToken')
+                       ->with('validtoken')
+                       ->willReturn($share);
+
+               // Test with a password protected share and no authentication
+               $response = $this->shareController->downloadShare('validtoken');
+               $expectedResponse = new DataResponse('Share is read-only');
+               $this->assertEquals($expectedResponse, $response);
+       }
+
+}
diff --git a/apps/files_sharing/tests/Controllers/ExternalShareControllerTest.php b/apps/files_sharing/tests/Controllers/ExternalShareControllerTest.php
deleted file mode 100644 (file)
index e5fd739..0000000
+++ /dev/null
@@ -1,156 +0,0 @@
-<?php
-/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- *
- * @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 OCA\Files_Sharing\Tests\Controllers;
-
-use OCA\Files_Sharing\Controllers\ExternalSharesController;
-use OCP\AppFramework\Http\DataResponse;
-use OCP\AppFramework\Http\JSONResponse;
-use OCP\Http\Client\IClientService;
-use OCP\IRequest;
-
-/**
- * Class ExternalShareControllerTest
- *
- * @package OCA\Files_Sharing\Controllers
- */
-class ExternalShareControllerTest extends \Test\TestCase {
-       /** @var IRequest */
-       private $request;
-       /** @var \OCA\Files_Sharing\External\Manager */
-       private $externalManager;
-       /** @var IClientService */
-       private $clientService;
-
-       public function setUp() {
-               parent::setUp();
-               $this->request = $this->getMockBuilder('\\OCP\\IRequest')
-                       ->disableOriginalConstructor()->getMock();
-               $this->externalManager = $this->getMockBuilder('\\OCA\\Files_Sharing\\External\\Manager')
-                       ->disableOriginalConstructor()->getMock();
-               $this->clientService = $this->getMockBuilder('\\OCP\Http\\Client\\IClientService')
-                       ->disableOriginalConstructor()->getMock();
-       }
-
-       /**
-        * @return ExternalSharesController
-        */
-       public function getExternalShareController() {
-               return new ExternalSharesController(
-                       'files_sharing',
-                       $this->request,
-                       $this->externalManager,
-                       $this->clientService
-               );
-       }
-
-       public function testIndex() {
-               $this->externalManager
-                       ->expects($this->once())
-                       ->method('getOpenShares')
-                       ->will($this->returnValue(['MyDummyArray']));
-
-               $this->assertEquals(new JSONResponse(['MyDummyArray']), $this->getExternalShareController()->index());
-       }
-
-       public function testCreate() {
-               $this->externalManager
-                       ->expects($this->once())
-                       ->method('acceptShare')
-                       ->with(4);
-
-               $this->assertEquals(new JSONResponse(), $this->getExternalShareController()->create(4));
-       }
-
-       public function testDestroy() {
-               $this->externalManager
-                       ->expects($this->once())
-                       ->method('declineShare')
-                       ->with(4);
-
-               $this->assertEquals(new JSONResponse(), $this->getExternalShareController()->destroy(4));
-       }
-
-       public function testRemoteWithValidHttps() {
-               $client = $this->getMockBuilder('\\OCP\\Http\\Client\\IClient')
-                       ->disableOriginalConstructor()->getMock();
-               $response = $this->getMockBuilder('\\OCP\\Http\\Client\\IResponse')
-                       ->disableOriginalConstructor()->getMock();
-               $response
-                       ->expects($this->exactly(2))
-                       ->method('getBody')
-                       ->will($this->onConsecutiveCalls('Certainly not a JSON string', '{"installed":true,"maintenance":false,"version":"8.1.0.8","versionstring":"8.1.0","edition":""}'));
-               $client
-                       ->expects($this->any())
-                       ->method('get')
-                       ->will($this->returnValue($response));
-
-               $this->clientService
-                       ->expects($this->exactly(2))
-                       ->method('newClient')
-                       ->will($this->returnValue($client));
-
-               $this->assertEquals(new DataResponse('https'), $this->getExternalShareController()->testRemote('owncloud.org'));
-       }
-
-       public function testRemoteWithWorkingHttp() {
-               $client = $this->getMockBuilder('\\OCP\\Http\\Client\\IClient')
-                       ->disableOriginalConstructor()->getMock();
-               $response = $this->getMockBuilder('\\OCP\\Http\\Client\\IResponse')
-                       ->disableOriginalConstructor()->getMock();
-               $client
-                       ->method('get')
-                       ->will($this->returnValue($response));
-               $response
-                       ->expects($this->exactly(5))
-                       ->method('getBody')
-                       ->will($this->onConsecutiveCalls('Certainly not a JSON string', 'Certainly not a JSON string', 'Certainly not a JSON string', 'Certainly not a JSON string', '{"installed":true,"maintenance":false,"version":"8.1.0.8","versionstring":"8.1.0","edition":""}'));
-               $this->clientService
-                       ->expects($this->exactly(5))
-                       ->method('newClient')
-                       ->will($this->returnValue($client));
-
-               $this->assertEquals(new DataResponse('http'), $this->getExternalShareController()->testRemote('owncloud.org'));
-       }
-
-       public function testRemoteWithInvalidRemote() {
-               $client = $this->getMockBuilder('\\OCP\\Http\\Client\\IClient')
-                       ->disableOriginalConstructor()->getMock();
-               $response = $this->getMockBuilder('\\OCP\\Http\\Client\\IResponse')
-                       ->disableOriginalConstructor()->getMock();
-               $client
-                       ->method('get')
-                       ->will($this->returnValue($response));
-               $response
-                       ->expects($this->exactly(6))
-                       ->method('getBody')
-                       ->will($this->returnValue('Certainly not a JSON string'));
-               $this->clientService
-                       ->expects($this->exactly(6))
-                       ->method('newClient')
-                       ->will($this->returnValue($client));
-
-               $this->assertEquals(new DataResponse(false), $this->getExternalShareController()->testRemote('owncloud.org'));
-       }
-}
diff --git a/apps/files_sharing/tests/Controllers/ShareControllerTest.php b/apps/files_sharing/tests/Controllers/ShareControllerTest.php
deleted file mode 100644 (file)
index 94891d8..0000000
+++ /dev/null
@@ -1,502 +0,0 @@
-<?php
-/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Georg Ehrke <georg@owncloud.com>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Vincent Cloutier <vincent1cloutier@gmail.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 OCA\Files_Sharing\Tests\Controllers;
-
-use OC\Files\Filesystem;
-use OCA\FederatedFileSharing\FederatedShareProvider;
-use OCA\Files_Sharing\Controllers\ShareController;
-use OCP\AppFramework\Http\DataResponse;
-use OCP\Share\Exceptions\ShareNotFound;
-use OCP\AppFramework\Http\NotFoundResponse;
-use OCP\AppFramework\Http\RedirectResponse;
-use OCP\AppFramework\Http\TemplateResponse;
-use OCP\ISession;
-use OCP\IUserManager;
-use OCP\Security\ISecureRandom;
-use OCP\IURLGenerator;
-use Symfony\Component\EventDispatcher\EventDispatcherInterface;
-
-/**
- * @group DB
- *
- * @package OCA\Files_Sharing\Controllers
- */
-class ShareControllerTest extends \Test\TestCase {
-
-       /** @var string */
-       private $user;
-       /** @var string */
-       private $oldUser;
-
-       /** @var string */
-       private $appName = 'files_sharing';
-       /** @var ShareController */
-       private $shareController;
-       /** @var IURLGenerator | \PHPUnit_Framework_MockObject_MockObject */
-       private $urlGenerator;
-       /** @var ISession | \PHPUnit_Framework_MockObject_MockObject */
-       private $session;
-       /** @var \OCP\IPreview | \PHPUnit_Framework_MockObject_MockObject */
-       private $previewManager;
-       /** @var \OCP\IConfig | \PHPUnit_Framework_MockObject_MockObject */
-       private $config;
-       /** @var  \OC\Share20\Manager | \PHPUnit_Framework_MockObject_MockObject */
-       private $shareManager;
-       /** @var IUserManager | \PHPUnit_Framework_MockObject_MockObject */
-       private $userManager;
-       /** @var  FederatedShareProvider | \PHPUnit_Framework_MockObject_MockObject */
-       private $federatedShareProvider;
-       /** @var EventDispatcherInterface | \PHPUnit_Framework_MockObject_MockObject */
-       private $eventDispatcher;
-
-       protected function setUp() {
-               parent::setUp();
-               $this->appName = 'files_sharing';
-
-               $this->shareManager = $this->getMockBuilder('\OC\Share20\Manager')->disableOriginalConstructor()->getMock();
-               $this->urlGenerator = $this->getMockBuilder('\OCP\IURLGenerator')->getMock();
-               $this->session = $this->getMockBuilder('\OCP\ISession')->getMock();
-               $this->previewManager = $this->getMockBuilder('\OCP\IPreview')->getMock();
-               $this->config = $this->getMockBuilder('\OCP\IConfig')->getMock();
-               $this->userManager = $this->getMockBuilder('\OCP\IUserManager')->getMock();
-               $this->federatedShareProvider = $this->getMockBuilder('OCA\FederatedFileSharing\FederatedShareProvider')
-                       ->disableOriginalConstructor()->getMock();
-               $this->federatedShareProvider->expects($this->any())
-                       ->method('isOutgoingServer2serverShareEnabled')->willReturn(true);
-               $this->federatedShareProvider->expects($this->any())
-                       ->method('isIncomingServer2serverShareEnabled')->willReturn(true);
-               $this->eventDispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
-
-               $this->shareController = new \OCA\Files_Sharing\Controllers\ShareController(
-                       $this->appName,
-                       $this->getMockBuilder('\OCP\IRequest')->getMock(),
-                       $this->config,
-                       $this->urlGenerator,
-                       $this->userManager,
-                       $this->getMockBuilder('\OCP\ILogger')->getMock(),
-                       $this->getMockBuilder('\OCP\Activity\IManager')->getMock(),
-                       $this->shareManager,
-                       $this->session,
-                       $this->previewManager,
-                       $this->getMockBuilder('\OCP\Files\IRootFolder')->getMock(),
-                       $this->federatedShareProvider,
-                       $this->eventDispatcher,
-                       $this->getMockBuilder('\OCP\IL10N')->getMock(),
-                       $this->getMockBuilder('\OC_Defaults')->getMock()
-               );
-
-
-               // Store current user
-               $this->oldUser = \OC_User::getUser();
-
-               // Create a dummy user
-               $this->user = \OC::$server->getSecureRandom()->generate(12, ISecureRandom::CHAR_LOWER);
-
-               \OC::$server->getUserManager()->createUser($this->user, $this->user);
-               \OC_Util::tearDownFS();
-               $this->loginAsUser($this->user);
-       }
-
-       protected function tearDown() {
-               \OC_Util::tearDownFS();
-               \OC_User::setUserId('');
-               Filesystem::tearDown();
-               $user = \OC::$server->getUserManager()->get($this->user);
-               if ($user !== null) { $user->delete(); }
-               \OC_User::setIncognitoMode(false);
-
-               \OC::$server->getSession()->set('public_link_authenticated', '');
-
-               // Set old user
-               \OC_User::setUserId($this->oldUser);
-               \OC_Util::setupFS($this->oldUser);
-               parent::tearDown();
-       }
-
-       public function testShowAuthenticateNotAuthenticated() {
-               $share = \OC::$server->getShareManager()->newShare();
-
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('getShareByToken')
-                       ->with('token')
-                       ->willReturn($share);
-
-               $response = $this->shareController->showAuthenticate('token');
-               $expectedResponse =  new TemplateResponse($this->appName, 'authenticate', [], 'guest');
-               $this->assertEquals($expectedResponse, $response);
-       }
-
-       public function testShowAuthenticateAuthenticatedForDifferentShare() {
-               $share = \OC::$server->getShareManager()->newShare();
-               $share->setId(1);
-
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('getShareByToken')
-                       ->with('token')
-                       ->willReturn($share);
-
-               $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
-               $this->session->method('get')->with('public_link_authenticated')->willReturn('2');
-
-               $response = $this->shareController->showAuthenticate('token');
-               $expectedResponse =  new TemplateResponse($this->appName, 'authenticate', [], 'guest');
-               $this->assertEquals($expectedResponse, $response);
-       }
-
-       public function testShowAuthenticateCorrectShare() {
-               $share = \OC::$server->getShareManager()->newShare();
-               $share->setId(1);
-
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('getShareByToken')
-                       ->with('token')
-                       ->willReturn($share);
-
-               $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
-               $this->session->method('get')->with('public_link_authenticated')->willReturn('1');
-
-               $this->urlGenerator->expects($this->once())
-                       ->method('linkToRoute')
-                       ->with('files_sharing.sharecontroller.showShare', ['token' => 'token'])
-                       ->willReturn('redirect');
-
-               $response = $this->shareController->showAuthenticate('token');
-               $expectedResponse =  new RedirectResponse('redirect');
-               $this->assertEquals($expectedResponse, $response);
-       }
-
-       public function testAuthenticateInvalidToken() {
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('getShareByToken')
-                       ->with('token')
-                       ->will($this->throwException(new \OCP\Share\Exceptions\ShareNotFound()));
-
-               $response = $this->shareController->authenticate('token');
-               $expectedResponse =  new NotFoundResponse();
-               $this->assertEquals($expectedResponse, $response);
-       }
-
-       public function testAuthenticateValidPassword() {
-               $share = \OC::$server->getShareManager()->newShare();
-               $share->setId(42);
-
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('getShareByToken')
-                       ->with('token')
-                       ->willReturn($share);
-
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('checkPassword')
-                       ->with($share, 'validpassword')
-                       ->willReturn(true);
-
-               $this->session
-                       ->expects($this->once())
-                       ->method('set')
-                       ->with('public_link_authenticated', '42');
-
-               $this->urlGenerator->expects($this->once())
-                       ->method('linkToRoute')
-                       ->with('files_sharing.sharecontroller.showShare', ['token'=>'token'])
-                       ->willReturn('redirect');
-
-               $response = $this->shareController->authenticate('token', 'validpassword');
-               $expectedResponse =  new RedirectResponse('redirect');
-               $this->assertEquals($expectedResponse, $response);
-       }
-
-       public function testAuthenticateInvalidPassword() {
-               $share = \OC::$server->getShareManager()->newShare();
-               $share->setNodeId(100)
-                       ->setNodeType('file')
-                       ->setToken('token')
-                       ->setSharedBy('initiator')
-                       ->setId(42);
-
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('getShareByToken')
-                       ->with('token')
-                       ->willReturn($share);
-
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('checkPassword')
-                       ->with($share, 'invalidpassword')
-                       ->willReturn(false);
-
-               $this->session
-                       ->expects($this->never())
-                       ->method('set');
-
-               $hookListner = $this->getMockBuilder('Dummy')->setMethods(['access'])->getMock();
-               \OCP\Util::connectHook('OCP\Share', 'share_link_access',  $hookListner, 'access');
-
-               $hookListner->expects($this->once())
-                       ->method('access')
-                       ->with($this->callback(function(array $data) {
-                               return $data['itemType'] === 'file' &&
-                                       $data['itemSource'] === 100 &&
-                                       $data['uidOwner'] === 'initiator' &&
-                                       $data['token'] === 'token' &&
-                                       $data['errorCode'] === 403 &&
-                                       $data['errorMessage'] === 'Wrong password';
-                       }));
-
-               $response = $this->shareController->authenticate('token', 'invalidpassword');
-               $expectedResponse =  new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
-               $this->assertEquals($expectedResponse, $response);
-       }
-
-       public function testShowShareInvalidToken() {
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('getShareByToken')
-                       ->with('invalidtoken')
-                       ->will($this->throwException(new ShareNotFound()));
-
-               // Test without a not existing token
-               $response = $this->shareController->showShare('invalidtoken');
-               $expectedResponse =  new NotFoundResponse();
-               $this->assertEquals($expectedResponse, $response);
-       }
-
-       public function testShowShareNotAuthenticated() {
-               $share = \OC::$server->getShareManager()->newShare();
-               $share->setPassword('password');
-
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('getShareByToken')
-                       ->with('validtoken')
-                       ->willReturn($share);
-
-               $this->urlGenerator->expects($this->once())
-                       ->method('linkToRoute')
-                       ->with('files_sharing.sharecontroller.authenticate', ['token' => 'validtoken'])
-                       ->willReturn('redirect');
-
-               // Test without a not existing token
-               $response = $this->shareController->showShare('validtoken');
-               $expectedResponse = new RedirectResponse('redirect');
-               $this->assertEquals($expectedResponse, $response);
-       }
-
-
-       public function testShowShare() {
-               $owner = $this->getMockBuilder('OCP\IUser')->getMock();
-               $owner->method('getDisplayName')->willReturn('ownerDisplay');
-               $owner->method('getUID')->willReturn('ownerUID');
-
-               $file = $this->getMockBuilder('OCP\Files\File')->getMock();
-               $file->method('getName')->willReturn('file1.txt');
-               $file->method('getMimetype')->willReturn('text/plain');
-               $file->method('getSize')->willReturn(33);
-               $file->method('isReadable')->willReturn(true);
-               $file->method('isShareable')->willReturn(true);
-
-               $share = \OC::$server->getShareManager()->newShare();
-               $share->setId(42);
-               $share->setPassword('password')
-                       ->setShareOwner('ownerUID')
-                       ->setNode($file)
-                       ->setTarget('/file1.txt');
-
-               $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
-               $this->session->method('get')->with('public_link_authenticated')->willReturn('42');
-
-               $this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
-
-               $this->config->method('getSystemValue')
-                       ->willReturnMap(
-                               [
-                                       ['max_filesize_animated_gifs_public_sharing', 10, 10],
-                                       ['enable_previews', true, true],
-                                       ['preview_max_x', 1024, 1024],
-                                       ['preview_max_y', 1024, 1024],
-                               ]
-                       );
-               $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
-               $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
-
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('getShareByToken')
-                       ->with('token')
-                       ->willReturn($share);
-               $this->config
-                       ->expects($this->once())
-                       ->method('getAppValue')
-                       ->with('core', 'shareapi_public_link_disclaimertext', null)
-                       ->willReturn('My disclaimer text');
-
-               $this->userManager->method('get')->with('ownerUID')->willReturn($owner);
-
-               $this->eventDispatcher->expects($this->once())
-                       ->method('dispatch')
-                       ->with('OCA\Files_Sharing::loadAdditionalScripts');
-
-               $response = $this->shareController->showShare('token');
-               $sharedTmplParams = array(
-                       'displayName' => 'ownerDisplay',
-                       'owner' => 'ownerUID',
-                       'filename' => 'file1.txt',
-                       'directory_path' => '/file1.txt',
-                       'mimetype' => 'text/plain',
-                       'dirToken' => 'token',
-                       'sharingToken' => 'token',
-                       'server2serversharing' => true,
-                       'protected' => 'true',
-                       'dir' => '',
-                       'downloadURL' => null,
-                       'fileSize' => '33 B',
-                       'nonHumanFileSize' => 33,
-                       'maxSizeAnimateGif' => 10,
-                       'previewSupported' => true,
-                       'previewEnabled' => true,
-                       'previewMaxX' => 1024,
-                       'previewMaxY' => 1024,
-                       'hideFileList' => false,
-                       'shareOwner' => 'ownerDisplay',
-                       'disclaimer' => 'My disclaimer text',
-                       'shareUrl' => null,
-                       'previewImage' => null
-               );
-
-               $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
-               $csp->addAllowedFrameDomain('\'self\'');
-               $expectedResponse = new TemplateResponse($this->appName, 'public', $sharedTmplParams, 'base');
-               $expectedResponse->setContentSecurityPolicy($csp);
-
-               $this->assertEquals($expectedResponse, $response);
-       }
-
-       /**
-        * @expectedException \OCP\Files\NotFoundException
-        */
-       public function testShowShareInvalid() {
-               $owner = $this->getMockBuilder('OCP\IUser')->getMock();
-               $owner->method('getDisplayName')->willReturn('ownerDisplay');
-               $owner->method('getUID')->willReturn('ownerUID');
-
-               $file = $this->getMockBuilder('OCP\Files\File')->getMock();
-               $file->method('getName')->willReturn('file1.txt');
-               $file->method('getMimetype')->willReturn('text/plain');
-               $file->method('getSize')->willReturn(33);
-               $file->method('isShareable')->willReturn(false);
-               $file->method('isReadable')->willReturn(true);
-
-               $share = \OC::$server->getShareManager()->newShare();
-               $share->setId(42);
-               $share->setPassword('password')
-                       ->setShareOwner('ownerUID')
-                       ->setNode($file)
-                       ->setTarget('/file1.txt');
-
-               $this->session->method('exists')->with('public_link_authenticated')->willReturn(true);
-               $this->session->method('get')->with('public_link_authenticated')->willReturn('42');
-
-               $this->previewManager->method('isMimeSupported')->with('text/plain')->willReturn(true);
-
-               $this->config->method('getSystemValue')
-                       ->willReturnMap(
-                               [
-                                       ['max_filesize_animated_gifs_public_sharing', 10, 10],
-                                       ['enable_previews', true, true],
-                               ]
-                       );
-               $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
-               $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
-
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('getShareByToken')
-                       ->with('token')
-                       ->willReturn($share);
-
-               $this->userManager->method('get')->with('ownerUID')->willReturn($owner);
-
-               $this->shareController->showShare('token');
-       }
-
-       public function testDownloadShare() {
-               $share = $this->getMockBuilder('\OCP\Share\IShare')->getMock();
-               $share->method('getPassword')->willReturn('password');
-               $share
-                       ->expects($this->once())
-                       ->method('getPermissions')
-                       ->willReturn(\OCP\Constants::PERMISSION_READ);
-
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('getShareByToken')
-                       ->with('validtoken')
-                       ->willReturn($share);
-
-               $this->urlGenerator->expects($this->once())
-                       ->method('linkToRoute')
-                       ->with('files_sharing.sharecontroller.authenticate', ['token' => 'validtoken'])
-                       ->willReturn('redirect');
-
-               // Test with a password protected share and no authentication
-               $response = $this->shareController->downloadShare('validtoken');
-               $expectedResponse = new RedirectResponse('redirect');
-               $this->assertEquals($expectedResponse, $response);
-       }
-
-       public function testDownloadShareWithCreateOnlyShare() {
-               $share = $this->getMockBuilder('\OCP\Share\IShare')->getMock();
-               $share->method('getPassword')->willReturn('password');
-               $share
-                       ->expects($this->once())
-                       ->method('getPermissions')
-                       ->willReturn(\OCP\Constants::PERMISSION_CREATE);
-
-               $this->shareManager
-                       ->expects($this->once())
-                       ->method('getShareByToken')
-                       ->with('validtoken')
-                       ->willReturn($share);
-
-               // Test with a password protected share and no authentication
-               $response = $this->shareController->downloadShare('validtoken');
-               $expectedResponse = new DataResponse('Share is read-only');
-               $this->assertEquals($expectedResponse, $response);
-       }
-
-}