You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ShareController.php 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Daniel Calviño Sánchez <danxuliu@gmail.com>
  10. * @author Georg Ehrke <oc.list@georgehrke.com>
  11. * @author j3l11234 <297259024@qq.com>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author John Molakvoæ <skjnldsv@protonmail.com>
  14. * @author Jonas Sulzer <jonas@violoncello.ch>
  15. * @author Julius Härtl <jus@bitgrid.net>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author MartB <mart.b@outlook.de>
  18. * @author Maxence Lange <maxence@pontapreta.net>
  19. * @author Michael Weimann <mail@michael-weimann.eu>
  20. * @author Morris Jobke <hey@morrisjobke.de>
  21. * @author Piotr Filiciak <piotr@filiciak.pl>
  22. * @author Robin Appelman <robin@icewind.nl>
  23. * @author Roeland Jago Douma <roeland@famdouma.nl>
  24. * @author Sascha Sambale <mastixmc@gmail.com>
  25. * @author Thomas Müller <thomas.mueller@tmit.eu>
  26. * @author Vincent Petry <vincent@nextcloud.com>
  27. *
  28. * @license AGPL-3.0
  29. *
  30. * This code is free software: you can redistribute it and/or modify
  31. * it under the terms of the GNU Affero General Public License, version 3,
  32. * as published by the Free Software Foundation.
  33. *
  34. * This program is distributed in the hope that it will be useful,
  35. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  36. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  37. * GNU Affero General Public License for more details.
  38. *
  39. * You should have received a copy of the GNU Affero General Public License, version 3,
  40. * along with this program. If not, see <http://www.gnu.org/licenses/>
  41. *
  42. */
  43. namespace OCA\Files_Sharing\Controller;
  44. use OC\Security\CSP\ContentSecurityPolicy;
  45. use OC_Files;
  46. use OC_Util;
  47. use OCA\FederatedFileSharing\FederatedShareProvider;
  48. use OCA\Files_Sharing\Activity\Providers\Downloads;
  49. use OCA\Files_Sharing\Event\BeforeTemplateRenderedEvent;
  50. use OCA\Files_Sharing\Event\ShareLinkAccessedEvent;
  51. use OCA\Viewer\Event\LoadViewer;
  52. use OCP\Accounts\IAccountManager;
  53. use OCP\AppFramework\AuthPublicShareController;
  54. use OCP\AppFramework\Http\NotFoundResponse;
  55. use OCP\AppFramework\Http\Template\ExternalShareMenuAction;
  56. use OCP\AppFramework\Http\Template\LinkMenuAction;
  57. use OCP\AppFramework\Http\Template\PublicTemplateResponse;
  58. use OCP\AppFramework\Http\Template\SimpleMenuAction;
  59. use OCP\AppFramework\Http\TemplateResponse;
  60. use OCP\Defaults;
  61. use OCP\EventDispatcher\IEventDispatcher;
  62. use OCP\Files\Folder;
  63. use OCP\Files\IRootFolder;
  64. use OCP\Files\NotFoundException;
  65. use OCP\IConfig;
  66. use OCP\IL10N;
  67. use OCP\ILogger;
  68. use OCP\IPreview;
  69. use OCP\IRequest;
  70. use OCP\ISession;
  71. use OCP\IURLGenerator;
  72. use OCP\IUser;
  73. use OCP\IUserManager;
  74. use OCP\Share;
  75. use OCP\Share\Exceptions\ShareNotFound;
  76. use OCP\Share\IManager as ShareManager;
  77. use OCP\Share\IShare;
  78. use OCP\Template;
  79. /**
  80. * Class ShareController
  81. *
  82. * @package OCA\Files_Sharing\Controllers
  83. */
  84. class ShareController extends AuthPublicShareController {
  85. /** @var IConfig */
  86. protected $config;
  87. /** @var IUserManager */
  88. protected $userManager;
  89. /** @var ILogger */
  90. protected $logger;
  91. /** @var \OCP\Activity\IManager */
  92. protected $activityManager;
  93. /** @var IPreview */
  94. protected $previewManager;
  95. /** @var IRootFolder */
  96. protected $rootFolder;
  97. /** @var FederatedShareProvider */
  98. protected $federatedShareProvider;
  99. /** @var IAccountManager */
  100. protected $accountManager;
  101. /** @var IEventDispatcher */
  102. protected $eventDispatcher;
  103. /** @var IL10N */
  104. protected $l10n;
  105. /** @var Defaults */
  106. protected $defaults;
  107. /** @var ShareManager */
  108. protected $shareManager;
  109. /** @var Share\IShare */
  110. protected $share;
  111. /**
  112. * @param string $appName
  113. * @param IRequest $request
  114. * @param IConfig $config
  115. * @param IURLGenerator $urlGenerator
  116. * @param IUserManager $userManager
  117. * @param ILogger $logger
  118. * @param \OCP\Activity\IManager $activityManager
  119. * @param \OCP\Share\IManager $shareManager
  120. * @param ISession $session
  121. * @param IPreview $previewManager
  122. * @param IRootFolder $rootFolder
  123. * @param FederatedShareProvider $federatedShareProvider
  124. * @param IAccountManager $accountManager
  125. * @param IEventDispatcher $eventDispatcher
  126. * @param IL10N $l10n
  127. * @param Defaults $defaults
  128. */
  129. public function __construct(string $appName,
  130. IRequest $request,
  131. IConfig $config,
  132. IURLGenerator $urlGenerator,
  133. IUserManager $userManager,
  134. ILogger $logger,
  135. \OCP\Activity\IManager $activityManager,
  136. ShareManager $shareManager,
  137. ISession $session,
  138. IPreview $previewManager,
  139. IRootFolder $rootFolder,
  140. FederatedShareProvider $federatedShareProvider,
  141. IAccountManager $accountManager,
  142. IEventDispatcher $eventDispatcher,
  143. IL10N $l10n,
  144. Defaults $defaults) {
  145. parent::__construct($appName, $request, $session, $urlGenerator);
  146. $this->config = $config;
  147. $this->userManager = $userManager;
  148. $this->logger = $logger;
  149. $this->activityManager = $activityManager;
  150. $this->previewManager = $previewManager;
  151. $this->rootFolder = $rootFolder;
  152. $this->federatedShareProvider = $federatedShareProvider;
  153. $this->accountManager = $accountManager;
  154. $this->eventDispatcher = $eventDispatcher;
  155. $this->l10n = $l10n;
  156. $this->defaults = $defaults;
  157. $this->shareManager = $shareManager;
  158. }
  159. public const SHARE_ACCESS = 'access';
  160. public const SHARE_AUTH = 'auth';
  161. public const SHARE_DOWNLOAD = 'download';
  162. /**
  163. * @PublicPage
  164. * @NoCSRFRequired
  165. *
  166. * Show the authentication page
  167. * The form has to submit to the authenticate method route
  168. */
  169. public function showAuthenticate(): TemplateResponse {
  170. $templateParameters = ['share' => $this->share];
  171. $this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($this->share, BeforeTemplateRenderedEvent::SCOPE_PUBLIC_SHARE_AUTH));
  172. $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
  173. if ($this->share->getSendPasswordByTalk()) {
  174. $csp = new ContentSecurityPolicy();
  175. $csp->addAllowedConnectDomain('*');
  176. $csp->addAllowedMediaDomain('blob:');
  177. $response->setContentSecurityPolicy($csp);
  178. }
  179. return $response;
  180. }
  181. /**
  182. * The template to show when authentication failed
  183. */
  184. protected function showAuthFailed(): TemplateResponse {
  185. $templateParameters = ['share' => $this->share, 'wrongpw' => true];
  186. $this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($this->share, BeforeTemplateRenderedEvent::SCOPE_PUBLIC_SHARE_AUTH));
  187. $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
  188. if ($this->share->getSendPasswordByTalk()) {
  189. $csp = new ContentSecurityPolicy();
  190. $csp->addAllowedConnectDomain('*');
  191. $csp->addAllowedMediaDomain('blob:');
  192. $response->setContentSecurityPolicy($csp);
  193. }
  194. return $response;
  195. }
  196. protected function verifyPassword(string $password): bool {
  197. return $this->shareManager->checkPassword($this->share, $password);
  198. }
  199. protected function getPasswordHash(): string {
  200. return $this->share->getPassword();
  201. }
  202. public function isValidToken(): bool {
  203. try {
  204. $this->share = $this->shareManager->getShareByToken($this->getToken());
  205. } catch (ShareNotFound $e) {
  206. return false;
  207. }
  208. return true;
  209. }
  210. protected function isPasswordProtected(): bool {
  211. return $this->share->getPassword() !== null;
  212. }
  213. protected function authSucceeded() {
  214. // For share this was always set so it is still used in other apps
  215. $this->session->set('public_link_authenticated', (string)$this->share->getId());
  216. }
  217. protected function authFailed() {
  218. $this->emitAccessShareHook($this->share, 403, 'Wrong password');
  219. $this->emitShareAccessEvent($this->share, self::SHARE_AUTH, 403, 'Wrong password');
  220. }
  221. /**
  222. * throws hooks when a share is attempted to be accessed
  223. *
  224. * @param \OCP\Share\IShare|string $share the Share instance if available,
  225. * otherwise token
  226. * @param int $errorCode
  227. * @param string $errorMessage
  228. *
  229. * @throws \OCP\HintException
  230. * @throws \OC\ServerNotAvailableException
  231. *
  232. * @deprecated use OCP\Files_Sharing\Event\ShareLinkAccessedEvent
  233. */
  234. protected function emitAccessShareHook($share, int $errorCode = 200, string $errorMessage = '') {
  235. $itemType = $itemSource = $uidOwner = '';
  236. $token = $share;
  237. $exception = null;
  238. if ($share instanceof \OCP\Share\IShare) {
  239. try {
  240. $token = $share->getToken();
  241. $uidOwner = $share->getSharedBy();
  242. $itemType = $share->getNodeType();
  243. $itemSource = $share->getNodeId();
  244. } catch (\Exception $e) {
  245. // we log what we know and pass on the exception afterwards
  246. $exception = $e;
  247. }
  248. }
  249. \OC_Hook::emit(Share::class, 'share_link_access', [
  250. 'itemType' => $itemType,
  251. 'itemSource' => $itemSource,
  252. 'uidOwner' => $uidOwner,
  253. 'token' => $token,
  254. 'errorCode' => $errorCode,
  255. 'errorMessage' => $errorMessage
  256. ]);
  257. if (!is_null($exception)) {
  258. throw $exception;
  259. }
  260. }
  261. /**
  262. * Emit a ShareLinkAccessedEvent event when a share is accessed, downloaded, auth...
  263. */
  264. protected function emitShareAccessEvent(IShare $share, string $step = '', int $errorCode = 200, string $errorMessage = ''): void {
  265. if ($step !== self::SHARE_ACCESS &&
  266. $step !== self::SHARE_AUTH &&
  267. $step !== self::SHARE_DOWNLOAD) {
  268. return;
  269. }
  270. $this->eventDispatcher->dispatchTyped(new ShareLinkAccessedEvent($share, $step, $errorCode, $errorMessage));
  271. }
  272. /**
  273. * Validate the permissions of the share
  274. *
  275. * @param Share\IShare $share
  276. * @return bool
  277. */
  278. private function validateShare(\OCP\Share\IShare $share) {
  279. // If the owner is disabled no access to the linke is granted
  280. $owner = $this->userManager->get($share->getShareOwner());
  281. if ($owner === null || !$owner->isEnabled()) {
  282. return false;
  283. }
  284. // If the initiator of the share is disabled no access is granted
  285. $initiator = $this->userManager->get($share->getSharedBy());
  286. if ($initiator === null || !$initiator->isEnabled()) {
  287. return false;
  288. }
  289. return $share->getNode()->isReadable() && $share->getNode()->isShareable();
  290. }
  291. /**
  292. * @PublicPage
  293. * @NoCSRFRequired
  294. *
  295. *
  296. * @param string $path
  297. * @return TemplateResponse
  298. * @throws NotFoundException
  299. * @throws \Exception
  300. */
  301. public function showShare($path = ''): TemplateResponse {
  302. \OC_User::setIncognitoMode(true);
  303. // Check whether share exists
  304. try {
  305. $share = $this->shareManager->getShareByToken($this->getToken());
  306. } catch (ShareNotFound $e) {
  307. // The share does not exists, we do not emit an ShareLinkAccessedEvent
  308. $this->emitAccessShareHook($this->getToken(), 404, 'Share not found');
  309. throw new NotFoundException();
  310. }
  311. if (!$this->validateShare($share)) {
  312. throw new NotFoundException();
  313. }
  314. $shareNode = $share->getNode();
  315. // We can't get the path of a file share
  316. try {
  317. if ($shareNode instanceof \OCP\Files\File && $path !== '') {
  318. $this->emitAccessShareHook($share, 404, 'Share not found');
  319. $this->emitShareAccessEvent($share, self::SHARE_ACCESS, 404, 'Share not found');
  320. throw new NotFoundException();
  321. }
  322. } catch (\Exception $e) {
  323. $this->emitAccessShareHook($share, 404, 'Share not found');
  324. $this->emitShareAccessEvent($share, self::SHARE_ACCESS, 404, 'Share not found');
  325. throw $e;
  326. }
  327. $shareTmpl = [];
  328. $shareTmpl['owner'] = '';
  329. $shareTmpl['shareOwner'] = '';
  330. $owner = $this->userManager->get($share->getShareOwner());
  331. if ($owner instanceof IUser) {
  332. $ownerAccount = $this->accountManager->getAccount($owner);
  333. $ownerName = $ownerAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME);
  334. if ($ownerName->getScope() === IAccountManager::SCOPE_PUBLISHED) {
  335. $shareTmpl['owner'] = $owner->getUID();
  336. $shareTmpl['shareOwner'] = $owner->getDisplayName();
  337. }
  338. }
  339. $shareTmpl['filename'] = $shareNode->getName();
  340. $shareTmpl['directory_path'] = $share->getTarget();
  341. $shareTmpl['note'] = $share->getNote();
  342. $shareTmpl['mimetype'] = $shareNode->getMimetype();
  343. $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($shareNode->getMimetype());
  344. $shareTmpl['dirToken'] = $this->getToken();
  345. $shareTmpl['sharingToken'] = $this->getToken();
  346. $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
  347. $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
  348. $shareTmpl['dir'] = '';
  349. $shareTmpl['nonHumanFileSize'] = $shareNode->getSize();
  350. $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($shareNode->getSize());
  351. $shareTmpl['hideDownload'] = $share->getHideDownload();
  352. $hideFileList = false;
  353. if ($shareNode instanceof \OCP\Files\Folder) {
  354. $shareIsFolder = true;
  355. try {
  356. $folderNode = $shareNode->get($path);
  357. } catch (\OCP\Files\NotFoundException $e) {
  358. $this->emitAccessShareHook($share, 404, 'Share not found');
  359. $this->emitShareAccessEvent($share, self::SHARE_ACCESS, 404, 'Share not found');
  360. throw new NotFoundException();
  361. }
  362. $shareTmpl['dir'] = $shareNode->getRelativePath($folderNode->getPath());
  363. /*
  364. * The OC_Util methods require a view. This just uses the node API
  365. */
  366. $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
  367. if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
  368. $freeSpace = max($freeSpace, 0);
  369. } else {
  370. $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
  371. }
  372. $hideFileList = !($share->getPermissions() & \OCP\Constants::PERMISSION_READ);
  373. $maxUploadFilesize = $freeSpace;
  374. $folder = new Template('files', 'list', '');
  375. $folder->assign('dir', $shareNode->getRelativePath($folderNode->getPath()));
  376. $folder->assign('dirToken', $this->getToken());
  377. $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
  378. $folder->assign('isPublic', true);
  379. $folder->assign('hideFileList', $hideFileList);
  380. $folder->assign('publicUploadEnabled', 'no');
  381. // default to list view
  382. $folder->assign('showgridview', false);
  383. $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
  384. $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
  385. $folder->assign('freeSpace', $freeSpace);
  386. $folder->assign('usedSpacePercent', 0);
  387. $folder->assign('trash', false);
  388. $shareTmpl['folder'] = $folder->fetchPage();
  389. } else {
  390. $shareIsFolder = false;
  391. }
  392. // default to list view
  393. $shareTmpl['showgridview'] = false;
  394. $shareTmpl['hideFileList'] = $hideFileList;
  395. $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', [
  396. 'token' => $this->getToken(),
  397. 'filename' => $shareIsFolder ? null : $shareNode->getName()
  398. ]);
  399. $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $this->getToken()]);
  400. $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
  401. $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
  402. $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
  403. $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
  404. $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
  405. $shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
  406. if ($shareTmpl['previewSupported']) {
  407. $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview',
  408. ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 'token' => $shareTmpl['dirToken']]);
  409. $ogPreview = $shareTmpl['previewImage'];
  410. // We just have direct previews for image files
  411. if ($shareNode->getMimePart() === 'image') {
  412. $shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $this->getToken()]);
  413. $ogPreview = $shareTmpl['previewURL'];
  414. //Whatapp is kind of picky about their size requirements
  415. if ($this->request->isUserAgent(['/^WhatsApp/'])) {
  416. $ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
  417. 'token' => $this->getToken(),
  418. 'x' => 256,
  419. 'y' => 256,
  420. 'a' => true,
  421. ]);
  422. }
  423. }
  424. } else {
  425. $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
  426. $ogPreview = $shareTmpl['previewImage'];
  427. }
  428. // Load files we need
  429. \OCP\Util::addScript('files', 'semaphore');
  430. \OCP\Util::addScript('files', 'file-upload');
  431. \OCP\Util::addStyle('files_sharing', 'publicView');
  432. \OCP\Util::addScript('files_sharing', 'public');
  433. \OCP\Util::addScript('files_sharing', 'templates');
  434. \OCP\Util::addScript('files', 'fileactions');
  435. \OCP\Util::addScript('files', 'fileactionsmenu');
  436. \OCP\Util::addScript('files', 'jquery.fileupload');
  437. \OCP\Util::addScript('files_sharing', 'files_drop');
  438. if (isset($shareTmpl['folder'])) {
  439. // JS required for folders
  440. \OCP\Util::addStyle('files', 'merged');
  441. \OCP\Util::addScript('files', 'filesummary');
  442. \OCP\Util::addScript('files', 'templates');
  443. \OCP\Util::addScript('files', 'breadcrumb');
  444. \OCP\Util::addScript('files', 'fileinfomodel');
  445. \OCP\Util::addScript('files', 'newfilemenu');
  446. \OCP\Util::addScript('files', 'files');
  447. \OCP\Util::addScript('files', 'filemultiselectmenu');
  448. \OCP\Util::addScript('files', 'filelist');
  449. \OCP\Util::addScript('files', 'keyboardshortcuts');
  450. \OCP\Util::addScript('files', 'operationprogressbar');
  451. // Load Viewer scripts
  452. if (class_exists(LoadViewer::class)) {
  453. $this->eventDispatcher->dispatchTyped(new LoadViewer());
  454. }
  455. }
  456. // OpenGraph Support: http://ogp.me/
  457. \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
  458. \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
  459. \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
  460. \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
  461. \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
  462. \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
  463. $this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($share));
  464. $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
  465. $csp->addAllowedFrameDomain('\'self\'');
  466. $response = new PublicTemplateResponse($this->appName, 'public', $shareTmpl);
  467. $response->setHeaderTitle($shareTmpl['filename']);
  468. if ($shareTmpl['shareOwner'] !== '') {
  469. $response->setHeaderDetails($this->l10n->t('shared by %s', [$shareTmpl['shareOwner']]));
  470. }
  471. $isNoneFileDropFolder = $shareIsFolder === false || $share->getPermissions() !== \OCP\Constants::PERMISSION_CREATE;
  472. if ($isNoneFileDropFolder && !$share->getHideDownload()) {
  473. \OCP\Util::addScript('files_sharing', 'public_note');
  474. $downloadWhite = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $shareTmpl['downloadURL'], 0);
  475. $downloadAllWhite = new SimpleMenuAction('download', $this->l10n->t('Download all files'), 'icon-download-white', $shareTmpl['downloadURL'], 0);
  476. $download = new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']);
  477. $downloadAll = new SimpleMenuAction('download', $this->l10n->t('Download all files'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']);
  478. $directLink = new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $shareTmpl['previewURL']);
  479. // TRANSLATORS The placeholder refers to the software product name as in 'Add to your Nextcloud'
  480. $externalShare = new ExternalShareMenuAction($this->l10n->t('Add to your %s', [$this->defaults->getProductName()]), 'icon-external', $shareTmpl['owner'], $shareTmpl['shareOwner'], $shareTmpl['filename']);
  481. $responseComposer = [];
  482. if ($shareIsFolder) {
  483. $responseComposer[] = $downloadAllWhite;
  484. $responseComposer[] = $downloadAll;
  485. } else {
  486. $responseComposer[] = $downloadWhite;
  487. $responseComposer[] = $download;
  488. }
  489. $responseComposer[] = $directLink;
  490. if ($this->federatedShareProvider->isOutgoingServer2serverShareEnabled()) {
  491. $responseComposer[] = $externalShare;
  492. }
  493. $response->setHeaderActions($responseComposer);
  494. }
  495. $response->setContentSecurityPolicy($csp);
  496. $this->emitAccessShareHook($share);
  497. $this->emitShareAccessEvent($share, self::SHARE_ACCESS);
  498. return $response;
  499. }
  500. /**
  501. * @PublicPage
  502. * @NoCSRFRequired
  503. * @NoSameSiteCookieRequired
  504. *
  505. * @param string $token
  506. * @param string $files
  507. * @param string $path
  508. * @param string $downloadStartSecret
  509. * @return void|\OCP\AppFramework\Http\Response
  510. * @throws NotFoundException
  511. */
  512. public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
  513. \OC_User::setIncognitoMode(true);
  514. $share = $this->shareManager->getShareByToken($token);
  515. if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
  516. return new \OCP\AppFramework\Http\DataResponse('Share has no read permission');
  517. }
  518. $files_list = null;
  519. if (!is_null($files)) { // download selected files
  520. $files_list = json_decode($files);
  521. // in case we get only a single file
  522. if ($files_list === null) {
  523. $files_list = [$files];
  524. }
  525. // Just in case $files is a single int like '1234'
  526. if (!is_array($files_list)) {
  527. $files_list = [$files_list];
  528. }
  529. }
  530. if (!$this->validateShare($share)) {
  531. throw new NotFoundException();
  532. }
  533. $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  534. $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
  535. // Single file share
  536. if ($share->getNode() instanceof \OCP\Files\File) {
  537. // Single file download
  538. $this->singleFileDownloaded($share, $share->getNode());
  539. }
  540. // Directory share
  541. else {
  542. /** @var \OCP\Files\Folder $node */
  543. $node = $share->getNode();
  544. // Try to get the path
  545. if ($path !== '') {
  546. try {
  547. $node = $node->get($path);
  548. } catch (NotFoundException $e) {
  549. $this->emitAccessShareHook($share, 404, 'Share not found');
  550. $this->emitShareAccessEvent($share, self::SHARE_DOWNLOAD, 404, 'Share not found');
  551. return new NotFoundResponse();
  552. }
  553. }
  554. $originalSharePath = $userFolder->getRelativePath($node->getPath());
  555. if ($node instanceof \OCP\Files\File) {
  556. // Single file download
  557. $this->singleFileDownloaded($share, $share->getNode());
  558. } else {
  559. try {
  560. if (!empty($files_list)) {
  561. $this->fileListDownloaded($share, $files_list, $node);
  562. } else {
  563. // The folder is downloaded
  564. $this->singleFileDownloaded($share, $share->getNode());
  565. }
  566. } catch (NotFoundException $e) {
  567. return new NotFoundResponse();
  568. }
  569. }
  570. }
  571. /* FIXME: We should do this all nicely in OCP */
  572. OC_Util::tearDownFS();
  573. OC_Util::setupFS($share->getShareOwner());
  574. /**
  575. * this sets a cookie to be able to recognize the start of the download
  576. * the content must not be longer than 32 characters and must only contain
  577. * alphanumeric characters
  578. */
  579. if (!empty($downloadStartSecret)
  580. && !isset($downloadStartSecret[32])
  581. && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
  582. // FIXME: set on the response once we use an actual app framework response
  583. setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
  584. }
  585. $this->emitAccessShareHook($share);
  586. $this->emitShareAccessEvent($share, self::SHARE_DOWNLOAD);
  587. $server_params = [ 'head' => $this->request->getMethod() === 'HEAD' ];
  588. /**
  589. * Http range requests support
  590. */
  591. if (isset($_SERVER['HTTP_RANGE'])) {
  592. $server_params['range'] = $this->request->getHeader('Range');
  593. }
  594. // download selected files
  595. if (!is_null($files) && $files !== '') {
  596. // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
  597. // after dispatching the request which results in a "Cannot modify header information" notice.
  598. OC_Files::get($originalSharePath, $files_list, $server_params);
  599. exit();
  600. } else {
  601. // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
  602. // after dispatching the request which results in a "Cannot modify header information" notice.
  603. OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
  604. exit();
  605. }
  606. }
  607. /**
  608. * create activity for every downloaded file
  609. *
  610. * @param Share\IShare $share
  611. * @param array $files_list
  612. * @param \OCP\Files\Folder $node
  613. * @throws NotFoundException when trying to download a folder or multiple files of a "hide download" share
  614. */
  615. protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
  616. if ($share->getHideDownload() && count($files_list) > 1) {
  617. throw new NotFoundException('Downloading more than 1 file');
  618. }
  619. foreach ($files_list as $file) {
  620. $subNode = $node->get($file);
  621. $this->singleFileDownloaded($share, $subNode);
  622. }
  623. }
  624. /**
  625. * create activity if a single file was downloaded from a link share
  626. *
  627. * @param Share\IShare $share
  628. * @throws NotFoundException when trying to download a folder of a "hide download" share
  629. */
  630. protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
  631. if ($share->getHideDownload() && $node instanceof Folder) {
  632. throw new NotFoundException('Downloading a folder');
  633. }
  634. $fileId = $node->getId();
  635. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  636. $userNodeList = $userFolder->getById($fileId);
  637. $userNode = $userNodeList[0];
  638. $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  639. $userPath = $userFolder->getRelativePath($userNode->getPath());
  640. $ownerPath = $ownerFolder->getRelativePath($node->getPath());
  641. $parameters = [$userPath];
  642. if ($share->getShareType() === IShare::TYPE_EMAIL) {
  643. if ($node instanceof \OCP\Files\File) {
  644. $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
  645. } else {
  646. $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
  647. }
  648. $parameters[] = $share->getSharedWith();
  649. } else {
  650. if ($node instanceof \OCP\Files\File) {
  651. $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
  652. } else {
  653. $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
  654. }
  655. }
  656. $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
  657. if ($share->getShareOwner() !== $share->getSharedBy()) {
  658. $parameters[0] = $ownerPath;
  659. $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
  660. }
  661. }
  662. /**
  663. * publish activity
  664. *
  665. * @param string $subject
  666. * @param array $parameters
  667. * @param string $affectedUser
  668. * @param int $fileId
  669. * @param string $filePath
  670. */
  671. protected function publishActivity($subject,
  672. array $parameters,
  673. $affectedUser,
  674. $fileId,
  675. $filePath) {
  676. $event = $this->activityManager->generateEvent();
  677. $event->setApp('files_sharing')
  678. ->setType('public_links')
  679. ->setSubject($subject, $parameters)
  680. ->setAffectedUser($affectedUser)
  681. ->setObject('files', $fileId, $filePath);
  682. $this->activityManager->publish($event);
  683. }
  684. }