ViewController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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 OCA\Files\Activity\Helper;
  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\OpenAPI;
  19. use OCP\AppFramework\Http\ContentSecurityPolicy;
  20. use OCP\AppFramework\Http\RedirectResponse;
  21. use OCP\AppFramework\Http\Response;
  22. use OCP\AppFramework\Http\TemplateResponse;
  23. use OCP\AppFramework\Services\IInitialState;
  24. use OCP\Collaboration\Resources\LoadAdditionalScriptsEvent as ResourcesLoadAdditionalScriptsEvent;
  25. use OCP\EventDispatcher\IEventDispatcher;
  26. use OCP\Files\Folder;
  27. use OCP\Files\IRootFolder;
  28. use OCP\Files\NotFoundException;
  29. use OCP\Files\Template\ITemplateManager;
  30. use OCP\IConfig;
  31. use OCP\IL10N;
  32. use OCP\IRequest;
  33. use OCP\IURLGenerator;
  34. use OCP\IUserSession;
  35. use OCP\Share\IManager;
  36. /**
  37. * @package OCA\Files\Controller
  38. */
  39. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  40. class ViewController extends Controller {
  41. private IURLGenerator $urlGenerator;
  42. private IL10N $l10n;
  43. private IConfig $config;
  44. private IEventDispatcher $eventDispatcher;
  45. private IUserSession $userSession;
  46. private IAppManager $appManager;
  47. private IRootFolder $rootFolder;
  48. private Helper $activityHelper;
  49. private IInitialState $initialState;
  50. private ITemplateManager $templateManager;
  51. private IManager $shareManager;
  52. private UserConfig $userConfig;
  53. private ViewConfig $viewConfig;
  54. public function __construct(string $appName,
  55. IRequest $request,
  56. IURLGenerator $urlGenerator,
  57. IL10N $l10n,
  58. IConfig $config,
  59. IEventDispatcher $eventDispatcher,
  60. IUserSession $userSession,
  61. IAppManager $appManager,
  62. IRootFolder $rootFolder,
  63. Helper $activityHelper,
  64. IInitialState $initialState,
  65. ITemplateManager $templateManager,
  66. IManager $shareManager,
  67. UserConfig $userConfig,
  68. ViewConfig $viewConfig
  69. ) {
  70. parent::__construct($appName, $request);
  71. $this->urlGenerator = $urlGenerator;
  72. $this->l10n = $l10n;
  73. $this->config = $config;
  74. $this->eventDispatcher = $eventDispatcher;
  75. $this->userSession = $userSession;
  76. $this->appManager = $appManager;
  77. $this->rootFolder = $rootFolder;
  78. $this->activityHelper = $activityHelper;
  79. $this->initialState = $initialState;
  80. $this->templateManager = $templateManager;
  81. $this->shareManager = $shareManager;
  82. $this->userConfig = $userConfig;
  83. $this->viewConfig = $viewConfig;
  84. }
  85. /**
  86. * FIXME: Replace with non static code
  87. *
  88. * @return array
  89. * @throws \OCP\Files\NotFoundException
  90. */
  91. protected function getStorageInfo(string $dir = '/') {
  92. $rootInfo = \OC\Files\Filesystem::getFileInfo('/', false);
  93. return \OC_Helper::getStorageInfo($dir, $rootInfo ?: null);
  94. }
  95. /**
  96. * @NoCSRFRequired
  97. * @NoAdminRequired
  98. *
  99. * @param string $fileid
  100. * @return TemplateResponse|RedirectResponse
  101. */
  102. public function showFile(?string $fileid = null): Response {
  103. if (!$fileid) {
  104. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index'));
  105. }
  106. // This is the entry point from the `/f/{fileid}` URL which is hardcoded in the server.
  107. try {
  108. return $this->redirectToFile((int) $fileid);
  109. } catch (NotFoundException $e) {
  110. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index', ['fileNotFound' => true]));
  111. }
  112. }
  113. /**
  114. * @NoCSRFRequired
  115. * @NoAdminRequired
  116. * @UseSession
  117. *
  118. * @param string $dir
  119. * @param string $view
  120. * @param string $fileid
  121. * @param bool $fileNotFound
  122. * @return TemplateResponse|RedirectResponse
  123. */
  124. public function indexView($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  125. return $this->index($dir, $view, $fileid, $fileNotFound);
  126. }
  127. /**
  128. * @NoCSRFRequired
  129. * @NoAdminRequired
  130. * @UseSession
  131. *
  132. * @param string $dir
  133. * @param string $view
  134. * @param string $fileid
  135. * @param bool $fileNotFound
  136. * @return TemplateResponse|RedirectResponse
  137. */
  138. public function indexViewFileid($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  139. return $this->index($dir, $view, $fileid, $fileNotFound);
  140. }
  141. /**
  142. * @NoCSRFRequired
  143. * @NoAdminRequired
  144. * @UseSession
  145. *
  146. * @param string $dir
  147. * @param string $view
  148. * @param string $fileid
  149. * @param bool $fileNotFound
  150. * @return TemplateResponse|RedirectResponse
  151. */
  152. public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  153. if ($fileid !== null && $view !== 'trashbin') {
  154. try {
  155. return $this->redirectToFileIfInTrashbin((int) $fileid);
  156. } catch (NotFoundException $e) {
  157. }
  158. }
  159. // Load the files we need
  160. \OCP\Util::addInitScript('files', 'init');
  161. \OCP\Util::addStyle('files', 'merged');
  162. \OCP\Util::addScript('files', 'main');
  163. $userId = $this->userSession->getUser()->getUID();
  164. // Get all the user favorites to create a submenu
  165. try {
  166. $userFolder = $this->rootFolder->getUserFolder($userId);
  167. $favElements = $this->activityHelper->getFavoriteNodes($userId, true);
  168. $favElements = array_map(fn (Folder $node) => [
  169. 'fileid' => $node->getId(),
  170. 'path' => $userFolder->getRelativePath($node->getPath()),
  171. ], $favElements);
  172. } catch (\RuntimeException $e) {
  173. $favElements = [];
  174. }
  175. // If the file doesn't exists in the folder and
  176. // exists in only one occurrence, redirect to that file
  177. // in the correct folder
  178. if ($fileid && $dir !== '') {
  179. $baseFolder = $this->rootFolder->getUserFolder($userId);
  180. $nodes = $baseFolder->getById((int) $fileid);
  181. if (!empty($nodes)) {
  182. $nodePath = $baseFolder->getRelativePath($nodes[0]->getPath());
  183. $relativePath = $nodePath ? dirname($nodePath) : '';
  184. // If the requested path does not contain the file id
  185. // or if the requested path is not the file id itself
  186. if (count($nodes) === 1 && $relativePath !== $dir && $nodePath !== $dir) {
  187. return $this->redirectToFile((int) $fileid);
  188. }
  189. } else { // fileid does not exist anywhere
  190. $fileNotFound = true;
  191. }
  192. }
  193. try {
  194. // If view is files, we use the directory, otherwise we use the root storage
  195. $storageInfo = $this->getStorageInfo(($view === 'files' && $dir) ? $dir : '/');
  196. } catch(\Exception $e) {
  197. $storageInfo = $this->getStorageInfo();
  198. }
  199. $this->initialState->provideInitialState('storageStats', $storageInfo);
  200. $this->initialState->provideInitialState('config', $this->userConfig->getConfigs());
  201. $this->initialState->provideInitialState('viewConfigs', $this->viewConfig->getConfigs());
  202. $this->initialState->provideInitialState('favoriteFolders', $favElements);
  203. // File sorting user config
  204. $filesSortingConfig = json_decode($this->config->getUserValue($userId, 'files', 'files_sorting_configs', '{}'), true);
  205. $this->initialState->provideInitialState('filesSortingConfig', $filesSortingConfig);
  206. // Forbidden file characters
  207. $forbiddenCharacters = \OCP\Util::getForbiddenFileNameChars();
  208. $this->initialState->provideInitialState('forbiddenCharacters', $forbiddenCharacters);
  209. $event = new LoadAdditionalScriptsEvent();
  210. $this->eventDispatcher->dispatchTyped($event);
  211. $this->eventDispatcher->dispatchTyped(new ResourcesLoadAdditionalScriptsEvent());
  212. $this->eventDispatcher->dispatchTyped(new LoadSidebar());
  213. $this->eventDispatcher->dispatchTyped(new LoadSearchPlugins());
  214. // Load Viewer scripts
  215. if (class_exists(LoadViewer::class)) {
  216. $this->eventDispatcher->dispatchTyped(new LoadViewer());
  217. }
  218. $this->initialState->provideInitialState('templates_path', $this->templateManager->hasTemplateDirectory() ? $this->templateManager->getTemplatePath() : false);
  219. $this->initialState->provideInitialState('templates', $this->templateManager->listCreators());
  220. $response = new TemplateResponse(
  221. Application::APP_ID,
  222. 'index',
  223. );
  224. $policy = new ContentSecurityPolicy();
  225. $policy->addAllowedFrameDomain('\'self\'');
  226. // Allow preview service worker
  227. $policy->addAllowedWorkerSrcDomain('\'self\'');
  228. $response->setContentSecurityPolicy($policy);
  229. $this->provideInitialState($dir, $fileid);
  230. return $response;
  231. }
  232. /**
  233. * Add openFileInfo in initialState.
  234. * @param string $dir - the ?dir= URL param
  235. * @param string $fileid - the fileid URL param
  236. * @return void
  237. */
  238. private function provideInitialState(string $dir, ?string $fileid): void {
  239. if ($fileid === null) {
  240. return;
  241. }
  242. $user = $this->userSession->getUser();
  243. if ($user === null) {
  244. return;
  245. }
  246. $uid = $user->getUID();
  247. $userFolder = $this->rootFolder->getUserFolder($uid);
  248. $node = $userFolder->getFirstNodeById((int) $fileid);
  249. if ($node === null) {
  250. return;
  251. }
  252. // properly format full path and make sure
  253. // we're relative to the user home folder
  254. $isRoot = $node === $userFolder;
  255. $path = $userFolder->getRelativePath($node->getPath());
  256. $directory = $userFolder->getRelativePath($node->getParent()->getPath());
  257. // Prevent opening a file from another folder.
  258. if ($dir !== $directory) {
  259. return;
  260. }
  261. $this->initialState->provideInitialState(
  262. 'fileInfo', [
  263. 'id' => $node->getId(),
  264. 'name' => $isRoot ? '' : $node->getName(),
  265. 'path' => $path,
  266. 'directory' => $directory,
  267. 'mime' => $node->getMimetype(),
  268. 'type' => $node->getType(),
  269. 'permissions' => $node->getPermissions(),
  270. ]
  271. );
  272. }
  273. /**
  274. * Redirects to the trashbin file list and highlight the given file id
  275. *
  276. * @param int $fileId file id to show
  277. * @return RedirectResponse redirect response or not found response
  278. * @throws NotFoundException
  279. */
  280. private function redirectToFileIfInTrashbin($fileId): RedirectResponse {
  281. $uid = $this->userSession->getUser()->getUID();
  282. $baseFolder = $this->rootFolder->getUserFolder($uid);
  283. $node = $baseFolder->getFirstNodeById($fileId);
  284. $params = [];
  285. if (!$node && $this->appManager->isEnabledForUser('files_trashbin')) {
  286. /** @var Folder */
  287. $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
  288. $node = $baseFolder->getFirstNodeById($fileId);
  289. $params['view'] = 'trashbin';
  290. if ($node) {
  291. $params['fileid'] = $fileId;
  292. if ($node instanceof Folder) {
  293. // set the full path to enter the folder
  294. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  295. } else {
  296. // set parent path as dir
  297. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  298. }
  299. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  300. }
  301. }
  302. throw new NotFoundException();
  303. }
  304. /**
  305. * Redirects to the file list and highlight the given file id
  306. *
  307. * @param int $fileId file id to show
  308. * @return RedirectResponse redirect response or not found response
  309. * @throws NotFoundException
  310. */
  311. private function redirectToFile(int $fileId) {
  312. $uid = $this->userSession->getUser()->getUID();
  313. $baseFolder = $this->rootFolder->getUserFolder($uid);
  314. $node = $baseFolder->getFirstNodeById($fileId);
  315. $params = ['view' => 'files'];
  316. try {
  317. $this->redirectToFileIfInTrashbin($fileId);
  318. } catch (NotFoundException $e) {
  319. }
  320. if ($node) {
  321. $params['fileid'] = $fileId;
  322. if ($node instanceof Folder) {
  323. // set the full path to enter the folder
  324. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  325. } else {
  326. // set parent path as dir
  327. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  328. }
  329. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  330. }
  331. throw new NotFoundException();
  332. }
  333. }