ViewController.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Files\Controller;
  8. use OC\Files\FilenameValidator;
  9. use OC\Files\Filesystem;
  10. use OCA\Files\AppInfo\Application;
  11. use OCA\Files\Event\LoadAdditionalScriptsEvent;
  12. use OCA\Files\Event\LoadSearchPlugins;
  13. use OCA\Files\Event\LoadSidebar;
  14. use OCA\Files\Service\UserConfig;
  15. use OCA\Files\Service\ViewConfig;
  16. use OCA\Viewer\Event\LoadViewer;
  17. use OCP\App\IAppManager;
  18. use OCP\AppFramework\Controller;
  19. use OCP\AppFramework\Http\Attribute\NoAdminRequired;
  20. use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
  21. use OCP\AppFramework\Http\Attribute\OpenAPI;
  22. use OCP\AppFramework\Http\ContentSecurityPolicy;
  23. use OCP\AppFramework\Http\RedirectResponse;
  24. use OCP\AppFramework\Http\Response;
  25. use OCP\AppFramework\Http\TemplateResponse;
  26. use OCP\AppFramework\Services\IInitialState;
  27. use OCP\Collaboration\Resources\LoadAdditionalScriptsEvent as ResourcesLoadAdditionalScriptsEvent;
  28. use OCP\EventDispatcher\IEventDispatcher;
  29. use OCP\Files\Folder;
  30. use OCP\Files\IRootFolder;
  31. use OCP\Files\NotFoundException;
  32. use OCP\Files\Template\ITemplateManager;
  33. use OCP\IConfig;
  34. use OCP\IL10N;
  35. use OCP\IRequest;
  36. use OCP\IURLGenerator;
  37. use OCP\IUserSession;
  38. use OCP\Util;
  39. /**
  40. * @package OCA\Files\Controller
  41. */
  42. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  43. class ViewController extends Controller {
  44. public function __construct(
  45. string $appName,
  46. IRequest $request,
  47. private IURLGenerator $urlGenerator,
  48. private IL10N $l10n,
  49. private IConfig $config,
  50. private IEventDispatcher $eventDispatcher,
  51. private IUserSession $userSession,
  52. private IAppManager $appManager,
  53. private IRootFolder $rootFolder,
  54. private IInitialState $initialState,
  55. private ITemplateManager $templateManager,
  56. private UserConfig $userConfig,
  57. private ViewConfig $viewConfig,
  58. private FilenameValidator $filenameValidator,
  59. ) {
  60. parent::__construct($appName, $request);
  61. }
  62. /**
  63. * FIXME: Replace with non static code
  64. *
  65. * @return array
  66. * @throws NotFoundException
  67. */
  68. protected function getStorageInfo(string $dir = '/') {
  69. $rootInfo = Filesystem::getFileInfo('/', false);
  70. return \OC_Helper::getStorageInfo($dir, $rootInfo ?: null);
  71. }
  72. /**
  73. * @param string $fileid
  74. * @return TemplateResponse|RedirectResponse
  75. */
  76. #[NoAdminRequired]
  77. #[NoCSRFRequired]
  78. public function showFile(?string $fileid = null): Response {
  79. if (!$fileid) {
  80. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
  81. }
  82. // This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
  83. try {
  84. return $this->redirectToFile((int)$fileid);
  85. } catch (NotFoundException $e) {
  86. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
  87. }
  88. }
  89. /**
  90. * @param string $dir
  91. * @param string $view
  92. * @param string $fileid
  93. * @param bool $fileNotFound
  94. * @return TemplateResponse|RedirectResponse
  95. */
  96. #[NoAdminRequired]
  97. #[NoCSRFRequired]
  98. public function indexView($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  99. return $this->index($dir, $view, $fileid, $fileNotFound);
  100. }
  101. /**
  102. * @param string $dir
  103. * @param string $view
  104. * @param string $fileid
  105. * @param bool $fileNotFound
  106. * @return TemplateResponse|RedirectResponse
  107. */
  108. #[NoAdminRequired]
  109. #[NoCSRFRequired]
  110. public function indexViewFileid($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  111. return $this->index($dir, $view, $fileid, $fileNotFound);
  112. }
  113. /**
  114. * @param string $dir
  115. * @param string $view
  116. * @param string $fileid
  117. * @param bool $fileNotFound
  118. * @return TemplateResponse|RedirectResponse
  119. */
  120. #[NoAdminRequired]
  121. #[NoCSRFRequired]
  122. public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  123. if ($fileid !== null && $view !== 'trashbin') {
  124. try {
  125. return $this->redirectToFileIfInTrashbin((int)$fileid);
  126. } catch (NotFoundException $e) {
  127. }
  128. }
  129. // Load the files we need
  130. Util::addInitScript('files', 'init');
  131. Util::addScript('files', 'main');
  132. $userId = $this->userSession->getUser()->getUID();
  133. // If the file doesn't exists in the folder and
  134. // exists in only one occurrence, redirect to that file
  135. // in the correct folder
  136. if ($fileid && $dir !== '') {
  137. $baseFolder = $this->rootFolder->getUserFolder($userId);
  138. $nodes = $baseFolder->getById((int)$fileid);
  139. if (!empty($nodes)) {
  140. $nodePath = $baseFolder->getRelativePath($nodes[0]->getPath());
  141. $relativePath = $nodePath ? dirname($nodePath) : '';
  142. // If the requested path does not contain the file id
  143. // or if the requested path is not the file id itself
  144. if (count($nodes) === 1 && $relativePath !== $dir && $nodePath !== $dir) {
  145. return $this->redirectToFile((int)$fileid);
  146. }
  147. } else { // fileid does not exist anywhere
  148. $fileNotFound = true;
  149. }
  150. }
  151. try {
  152. // If view is files, we use the directory, otherwise we use the root storage
  153. $storageInfo = $this->getStorageInfo(($view === 'files' && $dir) ? $dir : '/');
  154. } catch (\Exception $e) {
  155. $storageInfo = $this->getStorageInfo();
  156. }
  157. $this->initialState->provideInitialState('storageStats', $storageInfo);
  158. $this->initialState->provideInitialState('config', $this->userConfig->getConfigs());
  159. $this->initialState->provideInitialState('viewConfigs', $this->viewConfig->getConfigs());
  160. // File sorting user config
  161. $filesSortingConfig = json_decode($this->config->getUserValue($userId, 'files', 'files_sorting_configs', '{}'), true);
  162. $this->initialState->provideInitialState('filesSortingConfig', $filesSortingConfig);
  163. // Forbidden file characters (deprecated use capabilities)
  164. // TODO: Remove with next release of `@nextcloud/files`
  165. $forbiddenCharacters = $this->filenameValidator->getForbiddenCharacters();
  166. $this->initialState->provideInitialState('forbiddenCharacters', $forbiddenCharacters);
  167. $event = new LoadAdditionalScriptsEvent();
  168. $this->eventDispatcher->dispatchTyped($event);
  169. $this->eventDispatcher->dispatchTyped(new ResourcesLoadAdditionalScriptsEvent());
  170. $this->eventDispatcher->dispatchTyped(new LoadSidebar());
  171. $this->eventDispatcher->dispatchTyped(new LoadSearchPlugins());
  172. // Load Viewer scripts
  173. if (class_exists(LoadViewer::class)) {
  174. $this->eventDispatcher->dispatchTyped(new LoadViewer());
  175. }
  176. $this->initialState->provideInitialState('templates_path', $this->templateManager->hasTemplateDirectory() ? $this->templateManager->getTemplatePath() : false);
  177. $this->initialState->provideInitialState('templates', $this->templateManager->listCreators());
  178. $response = new TemplateResponse(
  179. Application::APP_ID,
  180. 'index',
  181. );
  182. $policy = new ContentSecurityPolicy();
  183. $policy->addAllowedFrameDomain('\'self\'');
  184. // Allow preview service worker
  185. $policy->addAllowedWorkerSrcDomain('\'self\'');
  186. $response->setContentSecurityPolicy($policy);
  187. return $response;
  188. }
  189. /**
  190. * Redirects to the trashbin file list and highlight the given file id
  191. *
  192. * @param int $fileId file id to show
  193. * @return RedirectResponse redirect response or not found response
  194. * @throws NotFoundException
  195. */
  196. private function redirectToFileIfInTrashbin($fileId): RedirectResponse {
  197. $uid = $this->userSession->getUser()->getUID();
  198. $baseFolder = $this->rootFolder->getUserFolder($uid);
  199. $node = $baseFolder->getFirstNodeById($fileId);
  200. $params = [];
  201. if (!$node && $this->appManager->isEnabledForUser('files_trashbin')) {
  202. /** @var Folder */
  203. $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
  204. $node = $baseFolder->getFirstNodeById($fileId);
  205. $params['view'] = 'trashbin';
  206. if ($node) {
  207. $params['fileid'] = $fileId;
  208. if ($node instanceof Folder) {
  209. // set the full path to enter the folder
  210. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  211. } else {
  212. // set parent path as dir
  213. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  214. }
  215. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  216. }
  217. }
  218. throw new NotFoundException();
  219. }
  220. /**
  221. * Redirects to the file list and highlight the given file id
  222. *
  223. * @param int $fileId file id to show
  224. * @return RedirectResponse redirect response or not found response
  225. * @throws NotFoundException
  226. */
  227. private function redirectToFile(int $fileId) {
  228. $uid = $this->userSession->getUser()->getUID();
  229. $baseFolder = $this->rootFolder->getUserFolder($uid);
  230. $node = $baseFolder->getFirstNodeById($fileId);
  231. $params = ['view' => 'files'];
  232. try {
  233. $this->redirectToFileIfInTrashbin($fileId);
  234. } catch (NotFoundException $e) {
  235. }
  236. if ($node) {
  237. $params['fileid'] = $fileId;
  238. if ($node instanceof Folder) {
  239. // set the full path to enter the folder
  240. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  241. } else {
  242. // set parent path as dir
  243. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  244. // open the file by default (opening the viewer)
  245. $params['openfile'] = 'true';
  246. }
  247. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  248. }
  249. throw new NotFoundException();
  250. }
  251. }