1
0

ViewController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. *
  117. * @param string $dir
  118. * @param string $view
  119. * @param string $fileid
  120. * @param bool $fileNotFound
  121. * @return TemplateResponse|RedirectResponse
  122. */
  123. public function indexView($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  124. return $this->index($dir, $view, $fileid, $fileNotFound);
  125. }
  126. /**
  127. * @NoCSRFRequired
  128. * @NoAdminRequired
  129. *
  130. * @param string $dir
  131. * @param string $view
  132. * @param string $fileid
  133. * @param bool $fileNotFound
  134. * @return TemplateResponse|RedirectResponse
  135. */
  136. public function indexViewFileid($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  137. return $this->index($dir, $view, $fileid, $fileNotFound);
  138. }
  139. /**
  140. * @NoCSRFRequired
  141. * @NoAdminRequired
  142. *
  143. * @param string $dir
  144. * @param string $view
  145. * @param string $fileid
  146. * @param bool $fileNotFound
  147. * @return TemplateResponse|RedirectResponse
  148. */
  149. public function index($dir = '', $view = '', $fileid = null, $fileNotFound = false) {
  150. if ($fileid !== null && $view !== 'trashbin') {
  151. try {
  152. return $this->redirectToFileIfInTrashbin((int) $fileid);
  153. } catch (NotFoundException $e) {
  154. }
  155. }
  156. // Load the files we need
  157. \OCP\Util::addInitScript('files', 'init');
  158. \OCP\Util::addStyle('files', 'merged');
  159. \OCP\Util::addScript('files', 'main');
  160. $userId = $this->userSession->getUser()->getUID();
  161. // Get all the user favorites to create a submenu
  162. try {
  163. $userFolder = $this->rootFolder->getUserFolder($userId);
  164. $favElements = $this->activityHelper->getFavoriteNodes($userId, true);
  165. $favElements = array_map(fn (Folder $node) => [
  166. 'fileid' => $node->getId(),
  167. 'path' => $userFolder->getRelativePath($node->getPath()),
  168. ], $favElements);
  169. } catch (\RuntimeException $e) {
  170. $favElements = [];
  171. }
  172. // If the file doesn't exists in the folder and
  173. // exists in only one occurrence, redirect to that file
  174. // in the correct folder
  175. if ($fileid && $dir !== '') {
  176. $baseFolder = $this->rootFolder->getUserFolder($userId);
  177. $nodes = $baseFolder->getById((int) $fileid);
  178. if (!empty($nodes)) {
  179. $nodePath = $baseFolder->getRelativePath($nodes[0]->getPath());
  180. $relativePath = $nodePath ? dirname($nodePath) : '';
  181. // If the requested path does not contain the file id
  182. // or if the requested path is not the file id itself
  183. if (count($nodes) === 1 && $relativePath !== $dir && $nodePath !== $dir) {
  184. return $this->redirectToFile((int) $fileid);
  185. }
  186. } else { // fileid does not exist anywhere
  187. $fileNotFound = true;
  188. }
  189. }
  190. try {
  191. // If view is files, we use the directory, otherwise we use the root storage
  192. $storageInfo = $this->getStorageInfo(($view === 'files' && $dir) ? $dir : '/');
  193. } catch(\Exception $e) {
  194. $storageInfo = $this->getStorageInfo();
  195. }
  196. $this->initialState->provideInitialState('storageStats', $storageInfo);
  197. $this->initialState->provideInitialState('config', $this->userConfig->getConfigs());
  198. $this->initialState->provideInitialState('viewConfigs', $this->viewConfig->getConfigs());
  199. $this->initialState->provideInitialState('favoriteFolders', $favElements);
  200. // File sorting user config
  201. $filesSortingConfig = json_decode($this->config->getUserValue($userId, 'files', 'files_sorting_configs', '{}'), true);
  202. $this->initialState->provideInitialState('filesSortingConfig', $filesSortingConfig);
  203. // Forbidden file characters
  204. $forbiddenCharacters = \OCP\Util::getForbiddenFileNameChars();
  205. $this->initialState->provideInitialState('forbiddenCharacters', $forbiddenCharacters);
  206. $event = new LoadAdditionalScriptsEvent();
  207. $this->eventDispatcher->dispatchTyped($event);
  208. $this->eventDispatcher->dispatchTyped(new ResourcesLoadAdditionalScriptsEvent());
  209. $this->eventDispatcher->dispatchTyped(new LoadSidebar());
  210. $this->eventDispatcher->dispatchTyped(new LoadSearchPlugins());
  211. // Load Viewer scripts
  212. if (class_exists(LoadViewer::class)) {
  213. $this->eventDispatcher->dispatchTyped(new LoadViewer());
  214. }
  215. $this->initialState->provideInitialState('templates_path', $this->templateManager->hasTemplateDirectory() ? $this->templateManager->getTemplatePath() : false);
  216. $this->initialState->provideInitialState('templates', $this->templateManager->listCreators());
  217. $response = new TemplateResponse(
  218. Application::APP_ID,
  219. 'index',
  220. );
  221. $policy = new ContentSecurityPolicy();
  222. $policy->addAllowedFrameDomain('\'self\'');
  223. // Allow preview service worker
  224. $policy->addAllowedWorkerSrcDomain('\'self\'');
  225. $response->setContentSecurityPolicy($policy);
  226. $this->provideInitialState($dir, $fileid);
  227. return $response;
  228. }
  229. /**
  230. * Add openFileInfo in initialState.
  231. * @param string $dir - the ?dir= URL param
  232. * @param string $fileid - the fileid URL param
  233. * @return void
  234. */
  235. private function provideInitialState(string $dir, ?string $fileid): void {
  236. if ($fileid === null) {
  237. return;
  238. }
  239. $user = $this->userSession->getUser();
  240. if ($user === null) {
  241. return;
  242. }
  243. $uid = $user->getUID();
  244. $userFolder = $this->rootFolder->getUserFolder($uid);
  245. $node = $userFolder->getFirstNodeById((int) $fileid);
  246. if ($node === null) {
  247. return;
  248. }
  249. // properly format full path and make sure
  250. // we're relative to the user home folder
  251. $isRoot = $node === $userFolder;
  252. $path = $userFolder->getRelativePath($node->getPath());
  253. $directory = $userFolder->getRelativePath($node->getParent()->getPath());
  254. // Prevent opening a file from another folder.
  255. if ($dir !== $directory) {
  256. return;
  257. }
  258. $this->initialState->provideInitialState(
  259. 'fileInfo', [
  260. 'id' => $node->getId(),
  261. 'name' => $isRoot ? '' : $node->getName(),
  262. 'path' => $path,
  263. 'directory' => $directory,
  264. 'mime' => $node->getMimetype(),
  265. 'type' => $node->getType(),
  266. 'permissions' => $node->getPermissions(),
  267. ]
  268. );
  269. }
  270. /**
  271. * Redirects to the trashbin file list and highlight the given file id
  272. *
  273. * @param int $fileId file id to show
  274. * @return RedirectResponse redirect response or not found response
  275. * @throws NotFoundException
  276. */
  277. private function redirectToFileIfInTrashbin($fileId): RedirectResponse {
  278. $uid = $this->userSession->getUser()->getUID();
  279. $baseFolder = $this->rootFolder->getUserFolder($uid);
  280. $node = $baseFolder->getFirstNodeById($fileId);
  281. $params = [];
  282. if (!$node && $this->appManager->isEnabledForUser('files_trashbin')) {
  283. /** @var Folder */
  284. $baseFolder = $this->rootFolder->get($uid . '/files_trashbin/files/');
  285. $node = $baseFolder->getFirstNodeById($fileId);
  286. $params['view'] = 'trashbin';
  287. if ($node) {
  288. $params['fileid'] = $fileId;
  289. if ($node instanceof Folder) {
  290. // set the full path to enter the folder
  291. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  292. } else {
  293. // set parent path as dir
  294. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  295. }
  296. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  297. }
  298. }
  299. throw new NotFoundException();
  300. }
  301. /**
  302. * Redirects to the file list and highlight the given file id
  303. *
  304. * @param int $fileId file id to show
  305. * @return RedirectResponse redirect response or not found response
  306. * @throws NotFoundException
  307. */
  308. private function redirectToFile(int $fileId) {
  309. $uid = $this->userSession->getUser()->getUID();
  310. $baseFolder = $this->rootFolder->getUserFolder($uid);
  311. $node = $baseFolder->getFirstNodeById($fileId);
  312. $params = ['view' => 'files'];
  313. try {
  314. $this->redirectToFileIfInTrashbin($fileId);
  315. } catch (NotFoundException $e) {
  316. }
  317. if ($node) {
  318. $params['fileid'] = $fileId;
  319. if ($node instanceof Folder) {
  320. // set the full path to enter the folder
  321. $params['dir'] = $baseFolder->getRelativePath($node->getPath());
  322. } else {
  323. // set parent path as dir
  324. $params['dir'] = $baseFolder->getRelativePath($node->getParent()->getPath());
  325. }
  326. return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.indexViewFileid', $params));
  327. }
  328. throw new NotFoundException();
  329. }
  330. }