1
0

ViewController.php 9.1 KB

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