ViewController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  7. * @author fnuesse <felix.nuesse@t-online.de>
  8. * @author fnuesse <fnuesse@techfak.uni-bielefeld.de>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author John Molakvoæ <skjnldsv@protonmail.com>
  11. * @author Julius Härtl <jus@bitgrid.net>
  12. * @author Lukas Reschke <lukas@statuscode.ch>
  13. * @author Max Kovalenko <mxss1998@yandex.ru>
  14. * @author Morris Jobke <hey@morrisjobke.de>
  15. * @author Nina Pypchenko <22447785+nina-py@users.noreply.github.com>
  16. * @author Robin Appelman <robin@icewind.nl>
  17. * @author Roeland Jago Douma <roeland@famdouma.nl>
  18. * @author Thomas Müller <thomas.mueller@tmit.eu>
  19. * @author Vincent Petry <vincent@nextcloud.com>
  20. *
  21. * @license AGPL-3.0
  22. *
  23. * This code is free software: you can redistribute it and/or modify
  24. * it under the terms of the GNU Affero General Public License, version 3,
  25. * as published by the Free Software Foundation.
  26. *
  27. * This program is distributed in the hope that it will be useful,
  28. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  29. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  30. * GNU Affero General Public License for more details.
  31. *
  32. * You should have received a copy of the GNU Affero General Public License, version 3,
  33. * along with this program. If not, see <http://www.gnu.org/licenses/>
  34. *
  35. */
  36. namespace OCA\Files\Controller;
  37. use OC\AppFramework\Http;
  38. use OCA\Files\Activity\Helper;
  39. use OCA\Files\AppInfo\Application;
  40. use OCA\Files\Event\LoadAdditionalScriptsEvent;
  41. use OCA\Files\Event\LoadSidebar;
  42. use OCA\Files\Service\UserConfig;
  43. use OCA\Files\Service\ViewConfig;
  44. use OCA\Viewer\Event\LoadViewer;
  45. use OCP\App\IAppManager;
  46. use OCP\AppFramework\Controller;
  47. use OCP\AppFramework\Http\Attribute\IgnoreOpenAPI;
  48. use OCP\AppFramework\Http\ContentSecurityPolicy;
  49. use OCP\AppFramework\Http\RedirectResponse;
  50. use OCP\AppFramework\Http\Response;
  51. use OCP\AppFramework\Http\TemplateResponse;
  52. use OCP\AppFramework\Services\IInitialState;
  53. use OCP\Collaboration\Resources\LoadAdditionalScriptsEvent as ResourcesLoadAdditionalScriptsEvent;
  54. use OCP\EventDispatcher\IEventDispatcher;
  55. use OCP\Files\Folder;
  56. use OCP\Files\IRootFolder;
  57. use OCP\Files\NotFoundException;
  58. use OCP\Files\Template\ITemplateManager;
  59. use OCP\IConfig;
  60. use OCP\IL10N;
  61. use OCP\IRequest;
  62. use OCP\IURLGenerator;
  63. use OCP\IUserSession;
  64. use OCP\Share\IManager;
  65. /**
  66. * @package OCA\Files\Controller
  67. */
  68. #[IgnoreOpenAPI]
  69. class ViewController extends Controller {
  70. private IURLGenerator $urlGenerator;
  71. private IL10N $l10n;
  72. private IConfig $config;
  73. private IEventDispatcher $eventDispatcher;
  74. private IUserSession $userSession;
  75. private IAppManager $appManager;
  76. private IRootFolder $rootFolder;
  77. private Helper $activityHelper;
  78. private IInitialState $initialState;
  79. private ITemplateManager $templateManager;
  80. private IManager $shareManager;
  81. private UserConfig $userConfig;
  82. private ViewConfig $viewConfig;
  83. public function __construct(string $appName,
  84. IRequest $request,
  85. IURLGenerator $urlGenerator,
  86. IL10N $l10n,
  87. IConfig $config,
  88. IEventDispatcher $eventDispatcher,
  89. IUserSession $userSession,
  90. IAppManager $appManager,
  91. IRootFolder $rootFolder,
  92. Helper $activityHelper,
  93. IInitialState $initialState,
  94. ITemplateManager $templateManager,
  95. IManager $shareManager,
  96. UserConfig $userConfig,
  97. ViewConfig $viewConfig
  98. ) {
  99. parent::__construct($appName, $request);
  100. $this->urlGenerator = $urlGenerator;
  101. $this->l10n = $l10n;
  102. $this->config = $config;
  103. $this->eventDispatcher = $eventDispatcher;
  104. $this->userSession = $userSession;
  105. $this->appManager = $appManager;
  106. $this->rootFolder = $rootFolder;
  107. $this->activityHelper = $activityHelper;
  108. $this->initialState = $initialState;
  109. $this->templateManager = $templateManager;
  110. $this->shareManager = $shareManager;
  111. $this->userConfig = $userConfig;
  112. $this->viewConfig = $viewConfig;
  113. }
  114. /**
  115. * @param string $appName
  116. * @param string $scriptName
  117. * @return string
  118. */
  119. protected function renderScript($appName, $scriptName) {
  120. $content = '';
  121. $appPath = \OC_App::getAppPath($appName);
  122. $scriptPath = $appPath . '/' . $scriptName;
  123. if (file_exists($scriptPath)) {
  124. // TODO: sanitize path / script name ?
  125. ob_start();
  126. include $scriptPath;
  127. $content = ob_get_contents();
  128. @ob_end_clean();
  129. }
  130. return $content;
  131. }
  132. /**
  133. * FIXME: Replace with non static code
  134. *
  135. * @return array
  136. * @throws \OCP\Files\NotFoundException
  137. */
  138. protected function getStorageInfo(string $dir = '/') {
  139. $rootInfo = \OC\Files\Filesystem::getFileInfo('/', false);
  140. return \OC_Helper::getStorageInfo($dir, $rootInfo ?: null);
  141. }
  142. /**
  143. * @NoCSRFRequired
  144. * @NoAdminRequired
  145. *
  146. * @param string $fileid
  147. * @return TemplateResponse|RedirectResponse
  148. */
  149. public function showFile(string $fileid = null): Response {
  150. if (!$fileid) {
  151. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
  152. }
  153. // This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
  154. try {
  155. return $this->redirectToFile((int) $fileid);
  156. } catch (NotFoundException $e) {
  157. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
  158. }
  159. }
  160. /**
  161. * @NoCSRFRequired
  162. * @NoAdminRequired
  163. * @UseSession
  164. *
  165. * @param string $dir
  166. * @param string $view
  167. * @param string $fileid
  168. * @param bool $fileNotFound
  169. * @return TemplateResponse|RedirectResponse
  170. */
  171. public function indexView($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  172. return $this->index($dir, $view, $fileid, $fileNotFound);
  173. }
  174. /**
  175. * @NoCSRFRequired
  176. * @NoAdminRequired
  177. * @UseSession
  178. *
  179. * @param string $dir
  180. * @param string $view
  181. * @param string $fileid
  182. * @param bool $fileNotFound
  183. * @return TemplateResponse|RedirectResponse
  184. */
  185. public function indexViewFileid($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  186. return $this->index($dir, $view, $fileid, $fileNotFound);
  187. }
  188. /**
  189. * @NoCSRFRequired
  190. * @NoAdminRequired
  191. * @UseSession
  192. *
  193. * @param string $dir
  194. * @param string $view
  195. * @param string $fileid
  196. * @param bool $fileNotFound
  197. * @return TemplateResponse|RedirectResponse
  198. */
  199. public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  200. if ($fileid !== null && $view !== 'trashbin') {
  201. try {
  202. return $this->redirectToFileIfInTrashbin((int) $fileid);
  203. } catch (NotFoundException $e) {}
  204. }
  205. // Load the files we need
  206. \OCP\Util::addStyle('files', 'merged');
  207. \OCP\Util::addScript('files', 'merged-index', 'files');
  208. \OCP\Util::addScript('files', 'main');
  209. $userId = $this->userSession->getUser()->getUID();
  210. // Get all the user favorites to create a submenu
  211. try {
  212. $favElements = $this->activityHelper->getFavoriteFilePaths($userId);
  213. } catch (\RuntimeException $e) {
  214. $favElements['folders'] = [];
  215. }
  216. try {
  217. // If view is files, we use the directory, otherwise we use the root storage
  218. $storageInfo = $this->getStorageInfo(($view === 'files' && $dir) ? $dir : '/');
  219. } catch(\Exception $e) {
  220. $storageInfo = $this->getStorageInfo();
  221. }
  222. $this->initialState->provideInitialState('storageStats', $storageInfo);
  223. $this->initialState->provideInitialState('config', $this->userConfig->getConfigs());
  224. $this->initialState->provideInitialState('viewConfigs', $this->viewConfig->getConfigs());
  225. $this->initialState->provideInitialState('favoriteFolders', $favElements['folders'] ?? []);
  226. // File sorting user config
  227. $filesSortingConfig = json_decode($this->config->getUserValue($userId, 'files', 'files_sorting_configs', '{}'), true);
  228. $this->initialState->provideInitialState('filesSortingConfig', $filesSortingConfig);
  229. $event = new LoadAdditionalScriptsEvent();
  230. $this->eventDispatcher->dispatchTyped($event);
  231. $this->eventDispatcher->dispatchTyped(new ResourcesLoadAdditionalScriptsEvent());
  232. $this->eventDispatcher->dispatchTyped(new LoadSidebar());
  233. // Load Viewer scripts
  234. if (class_exists(LoadViewer::class)) {
  235. $this->eventDispatcher->dispatchTyped(new LoadViewer());
  236. }
  237. $this->initialState->provideInitialState('templates_path', $this->templateManager->hasTemplateDirectory() ? $this->templateManager->getTemplatePath() : false);
  238. $this->initialState->provideInitialState('templates', $this->templateManager->listCreators());
  239. $params = [
  240. 'fileNotFound' => $fileNotFound ? 1 : 0
  241. ];
  242. $response = new TemplateResponse(
  243. Application::APP_ID,
  244. 'index',
  245. $params
  246. );
  247. $policy = new ContentSecurityPolicy();
  248. $policy->addAllowedFrameDomain('\'self\'');
  249. // Allow preview service worker
  250. $policy->addAllowedWorkerSrcDomain('\'self\'');
  251. $response->setContentSecurityPolicy($policy);
  252. $this->provideInitialState($dir, $fileid);
  253. return $response;
  254. }
  255. /**
  256. * Add openFileInfo in initialState.
  257. * @param string $dir - the ?dir= URL param
  258. * @param string $fileid - the fileid URL param
  259. * @return void
  260. */
  261. private function provideInitialState(string $dir, ?string $fileid): void {
  262. if ($fileid === null) {
  263. return;
  264. }
  265. $user = $this->userSession->getUser();
  266. if ($user === null) {
  267. return;
  268. }
  269. $uid = $user->getUID();
  270. $userFolder = $this->rootFolder->getUserFolder($uid);
  271. $nodes = $userFolder->getById((int) $fileid);
  272. $node = array_shift($nodes);
  273. if ($node === null) {
  274. return;
  275. }
  276. // properly format full path and make sure
  277. // we're relative to the user home folder
  278. $isRoot = $node === $userFolder;
  279. $path = $userFolder->getRelativePath($node->getPath());
  280. $directory = $userFolder->getRelativePath($node->getParent()->getPath());
  281. // Prevent opening a file from another folder.
  282. if ($dir !== $directory) {
  283. return;
  284. }
  285. $this->initialState->provideInitialState(
  286. 'openFileInfo', [
  287. 'id' => $node->getId(),
  288. 'name' => $isRoot ? '' : $node->getName(),
  289. 'path' => $path,
  290. 'directory' => $directory,
  291. 'mime' => $node->getMimetype(),
  292. 'type' => $node->getType(),
  293. 'permissions' => $node->getPermissions(),
  294. ]
  295. );
  296. }
  297. /**
  298. * Redirects to the trashbin file list and highlight the given file id
  299. *
  300. * @param int $fileId file id to show
  301. * @return RedirectResponse redirect response or not found response
  302. * @throws NotFoundException
  303. */
  304. private function redirectToFileIfInTrashbin($fileId): RedirectResponse {
  305. $uid = $this->userSession->getUser()->getUID();
  306. $baseFolder = $this->rootFolder->getUserFolder($uid);
  307. $nodes = $baseFolder->getById($fileId);
  308. $params = [];
  309. if (empty($nodes) && $this->appManager->isEnabledForUser('files_trashbin')) {
  310. /** @var Folder */
  311. $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
  312. $nodes = $baseFolder->getById($fileId);
  313. $params['view'] = 'trashbin';
  314. if (!empty($nodes)) {
  315. $node = current($nodes);
  316. $params['fileid'] = $fileId;
  317. if ($node instanceof Folder) {
  318. // set the full path to enter the folder
  319. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  320. } else {
  321. // set parent path as dir
  322. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  323. }
  324. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  325. }
  326. }
  327. throw new NotFoundException();
  328. }
  329. /**
  330. * Redirects to the file list and highlight the given file id
  331. *
  332. * @param int $fileId file id to show
  333. * @return RedirectResponse redirect response or not found response
  334. * @throws NotFoundException
  335. */
  336. private function redirectToFile(int $fileId) {
  337. $uid = $this->userSession->getUser()->getUID();
  338. $baseFolder = $this->rootFolder->getUserFolder($uid);
  339. $nodes = $baseFolder->getById($fileId);
  340. $params = [];
  341. try {
  342. $this->redirectToFileIfInTrashbin($fileId);
  343. } catch (NotFoundException $e) {}
  344. if (!empty($nodes)) {
  345. $node = current($nodes);
  346. $params['fileid'] = $fileId;
  347. if ($node instanceof Folder) {
  348. // set the full path to enter the folder
  349. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  350. } else {
  351. // set parent path as dir
  352. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  353. }
  354. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  355. }
  356. throw new NotFoundException();
  357. }
  358. }